<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Statistics on Stats and R</title>
    <link>https://statsandr.com/tags/statistics/</link>
    <description>Recent content in Statistics on Stats and R</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en</language>
    <lastBuildDate>Wed, 19 Aug 2026 00:00:00 +0000</lastBuildDate>
    
	<atom:link href="https://statsandr.com/tags/statistics/index.xml" rel="self" type="application/rss+xml" />
    
    
    <item>
      <title>McNemar&#39;s test in R</title>
      <link>https://statsandr.com/blog/mcnemars-test-in-r/</link>
      <pubDate>Wed, 19 Aug 2026 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/mcnemars-test-in-r/</guid>
      <description>


&lt;p&gt;&lt;img src=&#34;images/mcnemars-test-in-r.jpg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;In a previous article, we showed how to perform the &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;Chi-square test of independence in R&lt;/a&gt; in order to test whether two qualitative variables are related. As mentioned in that article (and in the one showing how to do the &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-by-hand/&#34;&gt;Chi-square test of independence by hand&lt;/a&gt;), this test requires that observations are &lt;strong&gt;independent&lt;/strong&gt;. When observations are dependent, that is, when the two measurements are collected on the &lt;em&gt;same&lt;/em&gt; subjects (paired samples), the McNemar’s or Cochran’s Q tests should be used instead.&lt;/p&gt;
&lt;p&gt;This article is dedicated to the first one: the &lt;strong&gt;McNemar’s test&lt;/strong&gt;. It is used to compare two related (paired) proportions measured on a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;qualitative variable&lt;/a&gt; with only two possible levels. In practice, it is mostly used when the same subjects are measured twice (typically before and after an intervention), or when two raters or two conditions are applied to the same subjects.&lt;/p&gt;
&lt;p&gt;In a way, the McNemar’s test is to two paired proportions what the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;paired Student’s t-test&lt;/a&gt; is to two paired means: in both cases we take advantage of the fact that the two measurements belong to the same individuals, the difference being that here the variable of interest is binary instead of quantitative.&lt;/p&gt;
&lt;p&gt;Note also that the McNemar’s test is limited to exactly two related measurements. If you have more than two (for example, the same question asked at three different time points), the appropriate extension is the Cochran’s Q test, of which the McNemar’s test is the special case for two measurements. If you are unsure about which test is appropriate for your own data, see this &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;overview of the most common statistical tests&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;In the remaining of the article, we present the data used for the illustration, the aim, hypotheses and assumptions of the test, and finally how to perform it in R and how to interpret its results.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;data&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Data&lt;/h1&gt;
&lt;p&gt;A dataset with a paired binary structure is not so easy to find among the datasets shipped with R, so we simulate our own data for this article.&lt;/p&gt;
&lt;p&gt;Suppose that we ask 200 randomly selected citizens whether they are in favor of a new policy in their city (answer “Yes” or “No”), that we then have them watch a public debate on this policy, and that we ask them exactly the same question again right after the debate:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# number of respondents
n &amp;lt;- 200

# opinion before the debate
before &amp;lt;- sample(c(&amp;quot;Yes&amp;quot;, &amp;quot;No&amp;quot;),
  size = n,
  replace = TRUE,
  prob = c(0.4, 0.6)
)

# opinion after the debate (respondents who were in favor
# tend to keep their opinion, while those who were against
# are more likely to change their mind)
after &amp;lt;- ifelse(before == &amp;quot;Yes&amp;quot;,
  sample(c(&amp;quot;Yes&amp;quot;, &amp;quot;No&amp;quot;), size = n, replace = TRUE, prob = c(0.9, 0.1)),
  sample(c(&amp;quot;Yes&amp;quot;, &amp;quot;No&amp;quot;), size = n, replace = TRUE, prob = c(0.4, 0.6))
)

# dataset
dat &amp;lt;- data.frame(
  respondent = 1:n,
  before = factor(before, levels = c(&amp;quot;Yes&amp;quot;, &amp;quot;No&amp;quot;)),
  after = factor(after, levels = c(&amp;quot;Yes&amp;quot;, &amp;quot;No&amp;quot;))
)

head(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   respondent before after
## 1          1    Yes   Yes
## 2          2    Yes   Yes
## 3          3     No   Yes
## 4          4    Yes   Yes
## 5          5    Yes   Yes
## 6          6     No    No&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;(Note that a seed has been set in the background with &lt;code&gt;set.seed(42)&lt;/code&gt;, so the simulated data and all results below are reproducible.)&lt;/p&gt;
&lt;p&gt;Each row corresponds to one respondent and contains two measurements of the same binary variable: the opinion before and the opinion after the debate. The two samples are thus paired, since the two answers on a given row belong to the same person.&lt;/p&gt;
&lt;p&gt;As always, it is a good practice to start with some &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt;. Here, the proportion of respondents in favor of the policy at each of the two time points:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# install.packages(&amp;quot;dplyr&amp;quot;)
library(dplyr)

dat %&amp;gt;%
  summarise(
    prop_before = mean(before == &amp;quot;Yes&amp;quot;),
    prop_after = mean(after == &amp;quot;Yes&amp;quot;)
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   prop_before prop_after
## 1        0.46       0.61&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In our sample, the proportion of respondents in favor of the policy went from 46% before the debate to 61% after the debate.&lt;/p&gt;
&lt;p&gt;These two proportions are computed on the same people, so comparing them as if they came from two independent groups would ignore the pairing. What matters for the McNemar’s test is the way each respondent moved (or did not move) from one answer to the other, and this information is contained in the 2 &lt;span class=&#34;math inline&#34;&gt;\(\times\)&lt;/span&gt; 2 contingency table of the paired answers:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;tab &amp;lt;- table(dat$before, dat$after,
  dnn = c(&amp;quot;Before&amp;quot;, &amp;quot;After&amp;quot;)
)

tab&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       After
## Before Yes No
##    Yes  81 11
##    No   41 67&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This table must be read pair by pair, and not cell by cell as we usually do:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the two cells on the diagonal are the &lt;strong&gt;concordant pairs&lt;/strong&gt;: 81 respondents answered “Yes” twice and 67 answered “No” twice, so these 148 respondents did not change their mind,&lt;/li&gt;
&lt;li&gt;the two cells outside the diagonal are the &lt;strong&gt;discordant pairs&lt;/strong&gt;: 11 respondents were in favor before the debate but against after, while 41 were against before but in favor after.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Only the discordant pairs carry information about a change of opinion (a respondent who gave twice the same answer tells us nothing about the effect of the debate), and this is precisely what the McNemar’s test is built on.&lt;/p&gt;
&lt;p&gt;The same information can be visualized with a simple barplot of the paired counts:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# install.packages(&amp;quot;ggplot2&amp;quot;)
library(ggplot2)

ggplot(dat) +
  aes(x = before, fill = after) +
  geom_bar(position = &amp;quot;dodge&amp;quot;) +
  labs(
    x = &amp;quot;Opinion before the debate&amp;quot;,
    y = &amp;quot;Number of respondents&amp;quot;,
    fill = &amp;quot;Opinion after the debate&amp;quot;
  )&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/mcnemars-test-in-r/index_files/figure-html/unnamed-chunk-4-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;From the table and the plot, we see that the changes of opinion do not balance out: many more respondents switched from “No” to “Yes” than the opposite. The question is now whether this imbalance is large enough to be declared significant, or whether it could reasonably be explained by chance alone (that is, by sampling fluctuations).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;mcnemars-test&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;McNemar’s test&lt;/h1&gt;
&lt;div id=&#34;aim-and-hypotheses&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Aim and hypotheses&lt;/h2&gt;
&lt;p&gt;The McNemar’s test is used to compare two related proportions, so it allows to determine whether the proportion of subjects belonging to a given category changed between two dependent measurements.&lt;/p&gt;
&lt;p&gt;The null and alternative hypotheses of the McNemar’s test are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: the two related proportions are equal (marginal homogeneity, that is, there is no systematic change between the two measurements)&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: the two related proportions are different (there is a significant change between the two measurements)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Since concordant pairs bring no information about a change, the test is based only on the two discordant cells. Denoting by &lt;span class=&#34;math inline&#34;&gt;\(b\)&lt;/span&gt; the number of subjects who answered “Yes” then “No”, and by &lt;span class=&#34;math inline&#34;&gt;\(c\)&lt;/span&gt; the number of subjects who answered “No” then “Yes”, the hypotheses can equivalently be written as:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0: p_b = p_c\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1: p_b \ne p_c\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(p_b\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(p_c\)&lt;/span&gt; are the probabilities of the two possible types of change. Under the null hypothesis, a change in one direction is as likely as a change in the other direction, so the test statistic&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\chi^2 = \frac{(b - c)^2}{b + c}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;follows a Chi-square distribution with 1 degree of freedom. By default, R applies a continuity correction (see more on this below), which replaces the numerator by &lt;span class=&#34;math inline&#34;&gt;\((|b - c| - 1)^2\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;In the context of our example, the McNemar’s test helps us to answer the following question: “Did the public debate significantly change the proportion of citizens in favor of the new policy?”.&lt;/p&gt;
&lt;p&gt;Rejecting &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt; would mean that the proportion of citizens in favor of the policy is significantly different before and after the debate, so that the changes of opinion observed in our sample are unlikely to be due to chance only. On the contrary, not rejecting &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt; would mean that we do not have enough evidence to conclude that opinions changed: the switches observed in the two directions would then be compatible with random fluctuations.&lt;/p&gt;
&lt;p&gt;Note that, as for many tests, the McNemar’s test does not indicate the &lt;em&gt;direction&lt;/em&gt; of the change. The direction must be read from the contingency table or from the marginal proportions computed in the previous section.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;assumptions&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Assumptions&lt;/h2&gt;
&lt;p&gt;For the results of the McNemar’s test to be valid, the following assumptions must be met:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;strong&gt;Paired measurements on a binary variable.&lt;/strong&gt; The two measurements must be collected on the same subjects, or on matched pairs (twins, or patients matched on age and sex for instance), and the variable of interest must be qualitative with exactly two levels (“Yes”/“No”, success/failure, present/absent, etc.). If the two samples are independent instead of paired, use the &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;Chi-square test of independence&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data organized in a 2 &lt;span class=&#34;math inline&#34;&gt;\(\times\)&lt;/span&gt; 2 contingency table of the paired outcomes.&lt;/strong&gt; Each subject contributes to one and only one cell of the table, so the sum of the four cells equals the number of subjects (200 in our case), and not twice this number.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Pairs are independent of each other.&lt;/strong&gt; Within a pair, the two measurements are of course dependent, and this is precisely the reason why we use this test. Between pairs, however, independence is required: one subject’s answers must not influence another subject’s answers. As for many statistical tests, this assumption is usually verified based on the design of the experiment rather than via a formal test. A random and representative &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;sample&lt;/a&gt; of the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;population&lt;/a&gt; of interest is generally sufficient. In our example, respondents have been selected at random and answered the question individually, so we consider this assumption as met.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Enough discordant pairs.&lt;/strong&gt; The &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value returned by &lt;code&gt;mcnemar.test()&lt;/code&gt; is based on a Chi-square approximation, which is reliable only if the number of discordant pairs is large enough. A common rule of thumb is that &lt;span class=&#34;math inline&#34;&gt;\(b + c\)&lt;/span&gt; should be at least 25. In our sample, &lt;span class=&#34;math inline&#34;&gt;\(b + c\)&lt;/span&gt; = 52, so the approximation can be used safely.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;When the number of discordant pairs is small, it is preferable to use the exact version of the test, which is based on a binomial distribution instead of the Chi-square approximation. It boils down to testing whether, among the discordant pairs, changes in one direction are as frequent as changes in the other direction, so it can be performed in base R with the &lt;code&gt;binom.test()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# exact version of the McNemar&amp;#39;s test
binom.test(tab[1, 2], tab[1, 2] + tab[2, 1], p = 0.5)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Exact binomial test
## 
## data:  tab[1, 2] and tab[1, 2] + tab[2, 1]
## number of successes = 11, number of trials = 52, p-value = 3.589e-05
## alternative hypothesis: true probability of success is not equal to 0.5
## 95 percent confidence interval:
##  0.1106115 0.3470376
## sample estimates:
## probability of success 
##              0.2115385&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the &lt;code&gt;{exact2x2}&lt;/code&gt; package also provides a dedicated &lt;code&gt;mcnemar.exact()&lt;/code&gt; function, which returns the same &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value together with a confidence interval for the odds ratio.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;In R&lt;/h2&gt;
&lt;p&gt;The McNemar’s test can be performed in R with the &lt;code&gt;mcnemar.test()&lt;/code&gt; function, applied on the contingency table of the paired outcomes:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mcnemar.test(tab)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	McNemar&amp;#39;s Chi-squared test with continuity correction
## 
## data:  tab
## McNemar&amp;#39;s chi-squared = 16.173, df = 1, p-value = 5.781e-05&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The test can also be applied directly on the two variables, without building the contingency table first (results are of course identical):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mcnemar.test(dat$before, dat$after)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	McNemar&amp;#39;s Chi-squared test with continuity correction
## 
## data:  dat$before and dat$after
## McNemar&amp;#39;s chi-squared = 16.173, df = 1, p-value = 5.781e-05&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output shows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the title of the test, together with the mention that a continuity correction has been applied,&lt;/li&gt;
&lt;li&gt;the data which have been used,&lt;/li&gt;
&lt;li&gt;the test statistic (&lt;code&gt;McNemar&#39;s chi-squared&lt;/code&gt;),&lt;/li&gt;
&lt;li&gt;the degrees of freedom (always equal to 1 for a 2 &lt;span class=&#34;math inline&#34;&gt;\(\times\)&lt;/span&gt; 2 table) and&lt;/li&gt;
&lt;li&gt;the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;As mentioned above, R applies a continuity correction by default. This correction makes the test slightly more conservative (that is, it gives a larger &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value), and it can be removed thanks to the &lt;code&gt;correct = FALSE&lt;/code&gt; argument:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mcnemar.test(tab, correct = FALSE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	McNemar&amp;#39;s Chi-squared test
## 
## data:  tab
## McNemar&amp;#39;s chi-squared = 17.308, df = 1, p-value = 3.179e-05&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With 52 discordant pairs, both versions lead to the same conclusion. The correction really matters only when the number of discordant pairs is small, and in that case the exact version presented in the previous section is a better option anyway.&lt;/p&gt;
&lt;p&gt;It is the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value which is of interest to conclude the test. If you are not familiar with &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values, I invite you to read this &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/#a-note-on-p-value-and-significance-level-alpha&#34;&gt;section&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;interpretations&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Interpretations&lt;/h2&gt;
&lt;p&gt;Based on the McNemar’s test, we reject the null hypothesis and we conclude that the proportion of citizens in favor of the new policy is significantly different before and after the debate (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &amp;lt; 0.001).&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(\Rightarrow\)&lt;/span&gt; In our context, rejecting the null hypothesis means that the debate is associated with a significant change of opinion. Looking at the direction of this change, the proportion of citizens in favor of the policy increased from 46% before the debate to 61% after the debate.&lt;/p&gt;
&lt;p&gt;(&lt;em&gt;For the sake of illustration&lt;/em&gt;, if the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value had been larger than the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;: we could not have rejected the null hypothesis, so we could not have concluded that the proportion of citizens in favor of the policy was different before and after the debate.)&lt;/p&gt;
&lt;p&gt;Contrary to the tests comparing three groups or more, no post-hoc test is required after a significant McNemar’s test: only two related measurements are compared, so a significant result already tells us which two proportions differ. Post-hoc comparisons become relevant again with more than two related measurements, in which case you should turn to the Cochran’s Q test.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;summary&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;In this article, we reviewed the aim and the hypotheses of the McNemar’s test, which is used to compare two related proportions measured on the same subjects, together with its underlying assumptions (paired measurements on a binary variable, independence between pairs and a sufficient number of discordant pairs). We then showed how to perform it in R with the &lt;code&gt;mcnemar.test()&lt;/code&gt; function, applied either on the 2 &lt;span class=&#34;math inline&#34;&gt;\(\times\)&lt;/span&gt; 2 contingency table of the paired answers or directly on the two variables, and how to interpret its results by comparing the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value with the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;. Remember that it is the special case of the Cochran’s Q test for exactly two related measurements, and that with independent samples the &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;Chi-square test of independence&lt;/a&gt; should be preferred.&lt;/p&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to understand the McNemar’s test and how to perform it in R.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>AssociationExplorer: A user-friendly shiny application for exploring associations and visual patterns</title>
      <link>https://statsandr.com/blog/associationexplorer-a-user-friendly-shiny-application-for-exploring-associations-and-visual-patterns/</link>
      <pubDate>Tue, 16 Dec 2025 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/associationexplorer-a-user-friendly-shiny-application-for-exploring-associations-and-visual-patterns/</guid>
      <description>


&lt;p&gt;&lt;img src=&#34;images/associationexplorer-a-user-friendly-shiny-application-for-exploring-associations-and-visual-patterns.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;I am pleased to announce the publication of our paper “AssociationExplorer: A user-friendly Shiny application for exploring associations and visual patterns” in the journal &lt;em&gt;SoftwareX&lt;/em&gt;, together with the official release of the AssociationExplorer2 R package on CRAN.&lt;/p&gt;
&lt;p&gt;Both the paper and the software are part of an open-science effort aimed at making exploratory data analysis more accessible to non-technical users.&lt;/p&gt;
&lt;div id=&#34;why-associationexplorer&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Why AssociationExplorer?&lt;/h2&gt;
&lt;p&gt;Exploring multivariate datasets is now central in social sciences, data journalism, and education. However, identifying and interpreting associations between variables often requires programming skills and a solid background in statistics, which can represent a substantial barrier for many users.&lt;/p&gt;
&lt;p&gt;AssociationExplorer was designed to lower this barrier by providing an interactive, visual, and statistically grounded tool for exploring associations between quantitative and qualitative variables, without requiring users to write any code.&lt;/p&gt;
&lt;p&gt;The application is primarily intended for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;journalists and data journalism practitioners,&lt;/li&gt;
&lt;li&gt;teachers and students,&lt;/li&gt;
&lt;li&gt;researchers in the exploratory phase of an analysis,&lt;/li&gt;
&lt;li&gt;engaged citizens interested in understanding public or survey data.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;what-does-the-app-do&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;What does the app do?&lt;/h2&gt;
&lt;p&gt;AssociationExplorer follows a simple and guided workflow:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Import data (CSV or Excel files)&lt;/li&gt;
&lt;li&gt;Interactively select variables of interest&lt;/li&gt;
&lt;li&gt;Automatically compute association measures adapted to variable types:
&lt;ul&gt;
&lt;li&gt;Pearson’s &lt;span class=&#34;math inline&#34;&gt;\(r\)&lt;/span&gt; correlation for numeric–numeric pairs,&lt;/li&gt;
&lt;li&gt;Cramer’s V for categorical–categorical pairs,&lt;/li&gt;
&lt;li&gt;the correlation ratio &lt;span class=&#34;math inline&#34;&gt;\(\eta\)&lt;/span&gt; for mixed numeric–categorical pairs&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Filter associations using user-defined thresholds&lt;/li&gt;
&lt;li&gt;Visualize results through:
&lt;ul&gt;
&lt;li&gt;an interactive correlation network,&lt;/li&gt;
&lt;li&gt;contextual bivariate visualizations (scatter plots, mean plots, and colored contingency tables)&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This workflow is designed to support transparent, reactive, and interpretable exploratory data analysis.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;a-paper-published-in-softwarex&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;A paper published in &lt;em&gt;SoftwareX&lt;/em&gt;&lt;/h2&gt;
&lt;p&gt;The &lt;em&gt;SoftwareX&lt;/em&gt; paper provides a detailed description of:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the motivation and intended audience of the tool,&lt;/li&gt;
&lt;li&gt;the software architecture,&lt;/li&gt;
&lt;li&gt;the methodological choices underlying the association measures,&lt;/li&gt;
&lt;li&gt;an illustrative case study based on the European Social Survey,&lt;/li&gt;
&lt;li&gt;and perspectives for future development.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Link to the paper: &lt;a href=&#34;https://doi.org/10.1016/j.softx.2025.102483&#34; class=&#34;uri&#34;&gt;https://doi.org/10.1016/j.softx.2025.102483&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In line with the journal’s standards, the code, documentation, and example data are fully open and reproducible.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;the-r-package-is-also-on-cran&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;The R package is also on CRAN&lt;/h2&gt;
&lt;p&gt;Alongside the paper, an R package is also available on CRAN, making installation and use straightforward:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;install.packages(&amp;quot;AssociationExplorer2&amp;quot;)
library(AssociationExplorer2)
run_associationexplorer()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The CRAN release ensures:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;standardized installation,&lt;/li&gt;
&lt;li&gt;better integration with existing R workflows,&lt;/li&gt;
&lt;li&gt;clearer versioning and dependency management.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;who-is-it-for-and-how-can-it-be-used&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Who is it for, and how can it be used?&lt;/h2&gt;
&lt;p&gt;AssociationExplorer is particularly useful for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;exploratory analysis prior to formal modeling,&lt;/li&gt;
&lt;li&gt;teaching concepts related to association and dependence,&lt;/li&gt;
&lt;li&gt;data storytelling and journalistic exploration,&lt;/li&gt;
&lt;li&gt;the analysis of survey data and public datasets.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The goal is not to replace confirmatory statistical analyses, but to provide a robust tool for understanding the structure of the data before modeling.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;acknowledgements&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Acknowledgements&lt;/h2&gt;
&lt;p&gt;This work was carried out in collaboration with Cédric Heuchenne, Arnaud Claes, and Antonin Descampe, whom I warmly thank.&lt;/p&gt;
&lt;p&gt;The project is supported by the Walloon Region and SPW Recherche within the ODALON research project.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;useful-links&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Useful links&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;📄 &lt;em&gt;SoftwareX&lt;/em&gt; paper: &lt;a href=&#34;https://doi.org/10.1016/j.softx.2025.102483&#34; class=&#34;uri&#34;&gt;https://doi.org/10.1016/j.softx.2025.102483&lt;/a&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;📦 CRAN package: &lt;a href=&#34;https://CRAN.R-project.org/package=AssociationExplorer2&#34; class=&#34;uri&#34;&gt;https://CRAN.R-project.org/package=AssociationExplorer2&lt;/a&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;💻 GitHub repository:
&lt;ul&gt;
&lt;li&gt;of the &lt;a href=&#34;https://github.com/AntoineSoetewey/AssociationExplorer&#34;&gt;paper&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;of the &lt;a href=&#34;https://github.com/AntoineSoetewey/AssociationExplorer2&#34;&gt;R package&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;As always, feedback, bug reports, and suggestions are very welcome.&lt;/p&gt;
&lt;p&gt;Thanks for reading!&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;References&lt;/h2&gt;
&lt;p&gt;Soetewey, A., Heuchenne, C., Claes, A. and Descampe, A. (2026). AssociationExplorer: A user-friendly shiny application for exploring associations and visual patterns. &lt;em&gt;SoftwareX, 33&lt;/em&gt;(102483). &lt;a href=&#34;https://doi.org/10.1016/j.softx.2025.102483&#34; class=&#34;uri&#34;&gt;https://doi.org/10.1016/j.softx.2025.102483&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Soetewey, A., Heuchenne, C., Claes, A. and Descampe, A. (2025). AssociationExplorer2: A User-Friendly ‘shiny’ Application for Exploring Associations and Visual Patterns. R package version 0.1.4, &lt;a href=&#34;https://github.com/AntoineSoetewey/AssociationExplorer2&#34; class=&#34;uri&#34;&gt;https://github.com/AntoineSoetewey/AssociationExplorer2&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Nonparametric serial interval estimation</title>
      <link>https://statsandr.com/blog/nonparametric-serial-interval-estimation/</link>
      <pubDate>Mon, 18 Aug 2025 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/nonparametric-serial-interval-estimation/</guid>
      <description>


&lt;div id=&#34;motivation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Motivation&lt;/h2&gt;
&lt;p&gt;Epidemiological delays inform about the time between two well-defined events related to a disease. The serial interval (SI) of an infectious disease is defined as the time between symptom onset in a primary case (infector) and symptom onset in a secondary case (infectee). It is a widely used epidemiological delay quantity and plays a central role in mathematical/statistical models of disease transmission. There exists a tight link between the reproduction number (average number of secondary infections generated by an infected individual) and the serial interval. Therefore, getting accurate knowledge about the SI distribution is key to gain a clear understanding of transmission dynamics during outbreaks. Timings of symptom onset for infector-infectee pairs can be obtained from line list data and observations usually consist of calendar dates. From a mathematical perspective, it is more convenient to work with numbers than with calendar dates and the latter are typically transformed to integers for the sake of statistical analysis.&lt;/p&gt;
&lt;p&gt;The main challenge when working with SI data is censoring in the sense that exact symptom onset times are usually unobserved and only known to have occurred between two time points. If the time resolution of a reported timing of illness onset is a calendar day, for instance July 15, there is not enough information to determine the exact time of illness onset within that day. As such, symptom onset is assumed to have occurred between July 15 and July 16 and we say that serial interval data are interval-censored. The figure below illustrates the coarse structure of SI data that adds a layer of complexity to the estimation problem.&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;images/SIcoarse.PNG&#34; style=&#34;width:100.0%&#34; alt=&#34;Source: Gressani O, Hens N. (2025). Nonparametric serial interval estimation with uniform mixtures. PLoS Comput Biol 21(8): e1013338.&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Source: Gressani O, Hens N. (2025). Nonparametric serial interval estimation with uniform mixtures. PLoS Comput Biol 21(8): e1013338.&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;A recent article by &lt;a href=&#34;https://doi.org/10.1371/journal.pcbi.1013338&#34;&gt;Gressani and Hens (2025)&lt;/a&gt; published in PLOS Computational Biology proposes a new estimator of the cumulative distribution function of the serial interval without making parametric assumptions regarding the underlying SI distribution. The estimator is based on mixtures of uniform distributions and only requires left and right bounds of serial interval windows of infector-infectee pairs as a main input (&lt;span class=&#34;math inline&#34;&gt;\(s_{iL}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(s_{iR}\)&lt;/span&gt; in the above figure). Point estimates of different serial interval features are available in closed-form and the bootstrap is used to compute confidence intervals. The nonparametric methodology is relatively simple and computationally fast and stable. Moreover, a user-friendly routine is available in the &lt;a href=&#34;https://github.com/oswaldogressani/EpiDelays&#34;&gt;EpiDelays package&lt;/a&gt; written in R. This post aims at giving users a simple first experience with this new nonparametric methodology for serial interval estimation. The package can be installed from GitHub (using devtools) as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;install.packages(&amp;quot;devtools&amp;quot;)
devtools::install_github(&amp;quot;oswaldogressani/EpiDelays&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;simulated-data&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Simulated data&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;estimSI()&lt;/code&gt; routine of the EpiDelays package can be used to compute nonparametric estimates (point estimates with standard errors and confidence intervals) of different serial interval features (e.g. the mean, median, standard deviation). The routine is simple to use and requires only two inputs:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;x&lt;/code&gt;: A data frame with &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; rows (corresponding to the number of transmission pairs for which illness onset data is available) and two columns containing the lower bound of the SI window &lt;span class=&#34;math inline&#34;&gt;\(s_{iL}\)&lt;/span&gt; (first column) and the upper bound of the SI window &lt;span class=&#34;math inline&#34;&gt;\(s_{iR}\)&lt;/span&gt; (second column).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;nboot&lt;/code&gt;: An integer for the bootstrap sample size (default is 2000) used to construct (&lt;span class=&#34;math inline&#34;&gt;\(90\%\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(95\%\)&lt;/span&gt;) confidence intervals (CIs).&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We start by illustrating the use of &lt;code&gt;estimSI()&lt;/code&gt; on simulated data. The &lt;code&gt;simSI()&lt;/code&gt; routine can be used to simulate artificial serial interval data with SI windows having a width (coarseness) of at least two days. The underlying target SI distribution is assumed to have a Gaussian distribution with mean &lt;code&gt;muS&lt;/code&gt; and standard deviation &lt;code&gt;sdS&lt;/code&gt; that have to be specified by the user. The code below can be used to generate &lt;span class=&#34;math inline&#34;&gt;\(n=15\)&lt;/span&gt; SI windows from a Gaussian distribution with a mean of &lt;span class=&#34;math inline&#34;&gt;\(3\)&lt;/span&gt; days and standard deviation of &lt;span class=&#34;math inline&#34;&gt;\(2\)&lt;/span&gt; days. More details regarding the data generating mechanism can be found in the &lt;a href=&#34;https://doi.org/10.1371/journal.pcbi.1013338&#34;&gt;article&lt;/a&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(2025)
simdata &amp;lt;- simSI(muS = 3, sdS = 2, n = 15)
gt::gt(round(simdata, 2))&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;kwsipvprqq&#34; style=&#34;padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;&#34;&gt;
&lt;style&gt;#kwsipvprqq table {
  font-family: system-ui, &#39;Segoe UI&#39;, Roboto, Helvetica, Arial, sans-serif, &#39;Apple Color Emoji&#39;, &#39;Segoe UI Emoji&#39;, &#39;Segoe UI Symbol&#39;, &#39;Noto Color Emoji&#39;;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

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

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

#kwsipvprqq .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;
}

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

#kwsipvprqq .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;
}

#kwsipvprqq .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;
}

#kwsipvprqq .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;
}

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

#kwsipvprqq .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;
}

#kwsipvprqq .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;
}

#kwsipvprqq .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;
}

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

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

#kwsipvprqq .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%;
}

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

#kwsipvprqq .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;
}

#kwsipvprqq .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;
}

#kwsipvprqq .gt_from_md &gt; :first-child {
  margin-top: 0;
}

#kwsipvprqq .gt_from_md &gt; :last-child {
  margin-bottom: 0;
}

#kwsipvprqq .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;
}

#kwsipvprqq .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;
}

#kwsipvprqq .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;
}

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

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

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

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

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

#kwsipvprqq .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;
}

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

#kwsipvprqq .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;
}

#kwsipvprqq .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;
}

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

#kwsipvprqq .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;
}

#kwsipvprqq .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;
}

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

#kwsipvprqq .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;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#kwsipvprqq div.Reactable &gt; div.rt-table &gt; div.rt-thead &gt; div.rt-tr.rt-tr-group-header &gt; div.rt-th-group:after {
  height: 0px !important;
}
&lt;/style&gt;
&lt;table class=&#34;gt_table&#34; data-quarto-disable-processing=&#34;false&#34; data-quarto-bootstrap=&#34;false&#34;&gt;
  &lt;thead&gt;
    &lt;tr class=&#34;gt_col_headings&#34;&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;s&#34;&gt;s&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;sl&#34;&gt;sl&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;sr&#34;&gt;sr&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;sw&#34;&gt;sw&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody class=&#34;gt_table_body&#34;&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;4.24&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;3&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;5&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;3.07&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;4&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;4.55&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;4&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;6&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;5.54&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;5&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;7&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;3.74&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;3&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;5&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;2.67&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;4&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;3.79&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;3&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;5&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;2.84&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;4&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;2.31&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;1&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;5&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;4&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;4.40&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;3&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;6&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;3&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;2.21&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;1&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;3&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;-0.51&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;-2&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;1&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;3&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;2.16&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;1&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;3&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;4.53&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;5&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;3&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;s&#34; class=&#34;gt_row gt_right&#34;&gt;5.13&lt;/td&gt;
&lt;td headers=&#34;sl&#34; class=&#34;gt_row gt_right&#34;&gt;3&lt;/td&gt;
&lt;td headers=&#34;sr&#34; class=&#34;gt_row gt_right&#34;&gt;7&lt;/td&gt;
&lt;td headers=&#34;sw&#34; class=&#34;gt_row gt_right&#34;&gt;4&lt;/td&gt;&lt;/tr&gt;
  &lt;/tbody&gt;
  
  
&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The first column of the simulated dataset contains the true (unobserved) serial interval value generated from the chosen Gaussian distribution. The second and third columns contain the left and right bound of the SI window (&lt;code&gt;sl&lt;/code&gt; and &lt;code&gt;sr&lt;/code&gt;). Finally, the last column contains the width of the observed SI window, i.e. &lt;code&gt;sw=sr-sl&lt;/code&gt;. The underlying target SI distribution is specified to be Gaussian with a mean of &lt;span class=&#34;math inline&#34;&gt;\(3\)&lt;/span&gt; days and standard deviation of &lt;span class=&#34;math inline&#34;&gt;\(2\)&lt;/span&gt; days. The 5th, 25th, 75th and 95th quantiles of the latter distribution are:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;round(qnorm(p = c(0.05, 0.25, 0.75, 0.95), mean = 3, sd = 2), 1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] -0.3  1.7  4.3  6.3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We now create a data frame containing &lt;code&gt;sl&lt;/code&gt; and &lt;code&gt;sr&lt;/code&gt; and use the latter as an input in the &lt;code&gt;estimSI()&lt;/code&gt; routine. Nonparametric estimates of different SI features can be accessed with &lt;code&gt;$npestim$&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;xdf &amp;lt;- data.frame(sl = simdata$sl, sr = simdata$sr)
SIfit &amp;lt;- estimSI(x = xdf, nboot = 2000)
gt::gt(round(SIfit$npestim, 1),
  rownames_to_stub = TRUE
)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;aomvniacfb&#34; style=&#34;padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;&#34;&gt;
&lt;style&gt;#aomvniacfb table {
  font-family: system-ui, &#39;Segoe UI&#39;, Roboto, Helvetica, Arial, sans-serif, &#39;Apple Color Emoji&#39;, &#39;Segoe UI Emoji&#39;, &#39;Segoe UI Symbol&#39;, &#39;Noto Color Emoji&#39;;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

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

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

#aomvniacfb .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;
}

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

#aomvniacfb .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;
}

#aomvniacfb .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;
}

#aomvniacfb .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;
}

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

#aomvniacfb .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;
}

#aomvniacfb .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;
}

#aomvniacfb .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;
}

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

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

#aomvniacfb .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%;
}

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

#aomvniacfb .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;
}

#aomvniacfb .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;
}

#aomvniacfb .gt_from_md &gt; :first-child {
  margin-top: 0;
}

#aomvniacfb .gt_from_md &gt; :last-child {
  margin-bottom: 0;
}

#aomvniacfb .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;
}

#aomvniacfb .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;
}

#aomvniacfb .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;
}

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

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

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

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

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

#aomvniacfb .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;
}

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

#aomvniacfb .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;
}

#aomvniacfb .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;
}

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

#aomvniacfb .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;
}

#aomvniacfb .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;
}

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

#aomvniacfb .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;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#aomvniacfb div.Reactable &gt; div.rt-table &gt; div.rt-thead &gt; div.rt-tr.rt-tr-group-header &gt; div.rt-th-group:after {
  height: 0px !important;
}
&lt;/style&gt;
&lt;table class=&#34;gt_table&#34; data-quarto-disable-processing=&#34;false&#34; data-quarto-bootstrap=&#34;false&#34;&gt;
  &lt;thead&gt;
    &lt;tr class=&#34;gt_col_headings&#34;&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;a::stub&#34;&gt;&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;mean&#34;&gt;mean&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;sd&#34;&gt;sd&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;q0.05&#34;&gt;q0.05&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;q0.25&#34;&gt;q0.25&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;q0.5&#34;&gt;q0.5&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;q0.75&#34;&gt;q0.75&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;q0.95&#34;&gt;q0.95&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody class=&#34;gt_table_body&#34;&gt;
    &lt;tr&gt;&lt;th id=&#34;stub_1_1&#34; scope=&#34;row&#34; class=&#34;gt_row gt_left gt_stub&#34;&gt;point&lt;/th&gt;
&lt;td headers=&#34;stub_1_1 mean&#34; class=&#34;gt_row gt_right&#34;&gt;3.4&lt;/td&gt;
&lt;td headers=&#34;stub_1_1 sd&#34; class=&#34;gt_row gt_right&#34;&gt;1.7&lt;/td&gt;
&lt;td headers=&#34;stub_1_1 q0.05&#34; class=&#34;gt_row gt_right&#34;&gt;0.3&lt;/td&gt;
&lt;td headers=&#34;stub_1_1 q0.25&#34; class=&#34;gt_row gt_right&#34;&gt;2.5&lt;/td&gt;
&lt;td headers=&#34;stub_1_1 q0.5&#34; class=&#34;gt_row gt_right&#34;&gt;3.5&lt;/td&gt;
&lt;td headers=&#34;stub_1_1 q0.75&#34; class=&#34;gt_row gt_right&#34;&gt;4.6&lt;/td&gt;
&lt;td headers=&#34;stub_1_1 q0.95&#34; class=&#34;gt_row gt_right&#34;&gt;6.0&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;th id=&#34;stub_1_2&#34; scope=&#34;row&#34; class=&#34;gt_row gt_left gt_stub&#34;&gt;se&lt;/th&gt;
&lt;td headers=&#34;stub_1_2 mean&#34; class=&#34;gt_row gt_right&#34;&gt;0.4&lt;/td&gt;
&lt;td headers=&#34;stub_1_2 sd&#34; class=&#34;gt_row gt_right&#34;&gt;0.3&lt;/td&gt;
&lt;td headers=&#34;stub_1_2 q0.05&#34; class=&#34;gt_row gt_right&#34;&gt;1.1&lt;/td&gt;
&lt;td headers=&#34;stub_1_2 q0.25&#34; class=&#34;gt_row gt_right&#34;&gt;0.4&lt;/td&gt;
&lt;td headers=&#34;stub_1_2 q0.5&#34; class=&#34;gt_row gt_right&#34;&gt;0.3&lt;/td&gt;
&lt;td headers=&#34;stub_1_2 q0.75&#34; class=&#34;gt_row gt_right&#34;&gt;0.4&lt;/td&gt;
&lt;td headers=&#34;stub_1_2 q0.95&#34; class=&#34;gt_row gt_right&#34;&gt;0.5&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;th id=&#34;stub_1_3&#34; scope=&#34;row&#34; class=&#34;gt_row gt_left gt_stub&#34;&gt;ci90l&lt;/th&gt;
&lt;td headers=&#34;stub_1_3 mean&#34; class=&#34;gt_row gt_right&#34;&gt;2.8&lt;/td&gt;
&lt;td headers=&#34;stub_1_3 sd&#34; class=&#34;gt_row gt_right&#34;&gt;1.1&lt;/td&gt;
&lt;td headers=&#34;stub_1_3 q0.05&#34; class=&#34;gt_row gt_right&#34;&gt;-1.3&lt;/td&gt;
&lt;td headers=&#34;stub_1_3 q0.25&#34; class=&#34;gt_row gt_right&#34;&gt;1.8&lt;/td&gt;
&lt;td headers=&#34;stub_1_3 q0.5&#34; class=&#34;gt_row gt_right&#34;&gt;2.9&lt;/td&gt;
&lt;td headers=&#34;stub_1_3 q0.75&#34; class=&#34;gt_row gt_right&#34;&gt;3.9&lt;/td&gt;
&lt;td headers=&#34;stub_1_3 q0.95&#34; class=&#34;gt_row gt_right&#34;&gt;5.0&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;th id=&#34;stub_1_4&#34; scope=&#34;row&#34; class=&#34;gt_row gt_left gt_stub&#34;&gt;ci90r&lt;/th&gt;
&lt;td headers=&#34;stub_1_4 mean&#34; class=&#34;gt_row gt_right&#34;&gt;4.0&lt;/td&gt;
&lt;td headers=&#34;stub_1_4 sd&#34; class=&#34;gt_row gt_right&#34;&gt;2.1&lt;/td&gt;
&lt;td headers=&#34;stub_1_4 q0.05&#34; class=&#34;gt_row gt_right&#34;&gt;2.1&lt;/td&gt;
&lt;td headers=&#34;stub_1_4 q0.25&#34; class=&#34;gt_row gt_right&#34;&gt;3.2&lt;/td&gt;
&lt;td headers=&#34;stub_1_4 q0.5&#34; class=&#34;gt_row gt_right&#34;&gt;4.1&lt;/td&gt;
&lt;td headers=&#34;stub_1_4 q0.75&#34; class=&#34;gt_row gt_right&#34;&gt;5.2&lt;/td&gt;
&lt;td headers=&#34;stub_1_4 q0.95&#34; class=&#34;gt_row gt_right&#34;&gt;6.6&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;th id=&#34;stub_1_5&#34; scope=&#34;row&#34; class=&#34;gt_row gt_left gt_stub&#34;&gt;ci95l&lt;/th&gt;
&lt;td headers=&#34;stub_1_5 mean&#34; class=&#34;gt_row gt_right&#34;&gt;2.7&lt;/td&gt;
&lt;td headers=&#34;stub_1_5 sd&#34; class=&#34;gt_row gt_right&#34;&gt;1.1&lt;/td&gt;
&lt;td headers=&#34;stub_1_5 q0.05&#34; class=&#34;gt_row gt_right&#34;&gt;-1.3&lt;/td&gt;
&lt;td headers=&#34;stub_1_5 q0.25&#34; class=&#34;gt_row gt_right&#34;&gt;1.5&lt;/td&gt;
&lt;td headers=&#34;stub_1_5 q0.5&#34; class=&#34;gt_row gt_right&#34;&gt;2.8&lt;/td&gt;
&lt;td headers=&#34;stub_1_5 q0.75&#34; class=&#34;gt_row gt_right&#34;&gt;3.8&lt;/td&gt;
&lt;td headers=&#34;stub_1_5 q0.95&#34; class=&#34;gt_row gt_right&#34;&gt;4.9&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;th id=&#34;stub_1_6&#34; scope=&#34;row&#34; class=&#34;gt_row gt_left gt_stub&#34;&gt;ci95r&lt;/th&gt;
&lt;td headers=&#34;stub_1_6 mean&#34; class=&#34;gt_row gt_right&#34;&gt;4.2&lt;/td&gt;
&lt;td headers=&#34;stub_1_6 sd&#34; class=&#34;gt_row gt_right&#34;&gt;2.2&lt;/td&gt;
&lt;td headers=&#34;stub_1_6 q0.05&#34; class=&#34;gt_row gt_right&#34;&gt;2.1&lt;/td&gt;
&lt;td headers=&#34;stub_1_6 q0.25&#34; class=&#34;gt_row gt_right&#34;&gt;3.3&lt;/td&gt;
&lt;td headers=&#34;stub_1_6 q0.5&#34; class=&#34;gt_row gt_right&#34;&gt;4.2&lt;/td&gt;
&lt;td headers=&#34;stub_1_6 q0.75&#34; class=&#34;gt_row gt_right&#34;&gt;5.4&lt;/td&gt;
&lt;td headers=&#34;stub_1_6 q0.95&#34; class=&#34;gt_row gt_right&#34;&gt;6.6&lt;/td&gt;&lt;/tr&gt;
  &lt;/tbody&gt;
  
  
&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The output shows point estimates (point), standard errors (se) and confidence intervals bounds (ci) for the serial interval mean, standard deviation (sd) and 5th, 25th, 50th, 75th and 95th quantiles denoted by q0.05, q0.25, etc. We can also plot the estimated cumulative distribution function (cdf) obtained with the nonparametric approach and compare it with the target Gaussian cdf. The quality of the fit will typically depend on the sample size &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; and on the degree of coarseness present in the data. Note that the nonparametric methodology naturally deals with negative SI values.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sl &amp;lt;- simdata$sl
sr &amp;lt;- simdata$sr
Fhat &amp;lt;- function(s) (1 / SIfit$n) * sum((s - sl) / (sr - sl) * (s &amp;gt;= sl &amp;amp; s &amp;lt;= sr) + (s &amp;gt; sr))
sf &amp;lt;- seq(-3, 8, length = 100)
plot(sf, sapply(sf, Fhat), type = &amp;quot;l&amp;quot;, lwd = 2, xlab = &amp;quot;Serial interval&amp;quot;, ylab = &amp;quot;cdf&amp;quot;)
grid()
lines(sf, pnorm(sf, mean = 3, sd = 2), col = &amp;quot;blue&amp;quot;, lwd = 2)
legend(&amp;quot;topleft&amp;quot;, c(&amp;quot;Estimated cdf of SI&amp;quot;, &amp;quot;Target cdf of SI&amp;quot;), col = c(&amp;quot;black&amp;quot;, &amp;quot;blue&amp;quot;), lwd = c(2, 2), bty = &amp;quot;n&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/nonparametric-serial-interval-estimation/index_files/figure-html/comparecdfs-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;real-data&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Real data&lt;/h2&gt;
&lt;p&gt;&lt;a href=&#34;https://www.nejm.org/doi/full/10.1056/NEJMoa0906089&#34;&gt;Lessler et al. (2009)&lt;/a&gt; share a dataset containing serial interval windows obtained from &lt;span class=&#34;math inline&#34;&gt;\(n=16\)&lt;/span&gt; infector-infectee pairs for Influenza A (2009 H1N1 influenza) at a New York City school. The SI windows are directly available from the supplementary appendix of the latter reference and are encoded in a data frame &lt;code&gt;xNY&lt;/code&gt;. Nonparametric estimates of serial interval features are then obtained with &lt;code&gt;estimSI()&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;xNY &amp;lt;- data.frame(sl = c(1, 1, 1, 0, 0, 4, 2, 3, 0, 3, 0, 3, 4, 1, 3, 3), sr = c(3, 3, 3, 2, 2, 6, 4, 5, 2, 5, 2, 5, 6, 3, 5, 5))
set.seed(123)
SIfitNY &amp;lt;- estimSI(xNY, nboot = 2000)
gt::gt(round(SIfitNY$npestim, 1),
  rownames_to_stub = TRUE
)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;lkmlioxfax&#34; style=&#34;padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;&#34;&gt;
&lt;style&gt;#lkmlioxfax table {
  font-family: system-ui, &#39;Segoe UI&#39;, Roboto, Helvetica, Arial, sans-serif, &#39;Apple Color Emoji&#39;, &#39;Segoe UI Emoji&#39;, &#39;Segoe UI Symbol&#39;, &#39;Noto Color Emoji&#39;;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

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

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

#lkmlioxfax .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;
}

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

#lkmlioxfax .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;
}

#lkmlioxfax .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;
}

#lkmlioxfax .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;
}

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

#lkmlioxfax .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;
}

#lkmlioxfax .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;
}

#lkmlioxfax .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;
}

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

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

#lkmlioxfax .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%;
}

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

#lkmlioxfax .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;
}

#lkmlioxfax .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;
}

#lkmlioxfax .gt_from_md &gt; :first-child {
  margin-top: 0;
}

#lkmlioxfax .gt_from_md &gt; :last-child {
  margin-bottom: 0;
}

#lkmlioxfax .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;
}

#lkmlioxfax .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;
}

#lkmlioxfax .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;
}

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

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

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

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

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

#lkmlioxfax .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;
}

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

#lkmlioxfax .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;
}

#lkmlioxfax .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;
}

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

#lkmlioxfax .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;
}

#lkmlioxfax .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;
}

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

#lkmlioxfax .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;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#lkmlioxfax div.Reactable &gt; div.rt-table &gt; div.rt-thead &gt; div.rt-tr.rt-tr-group-header &gt; div.rt-th-group:after {
  height: 0px !important;
}
&lt;/style&gt;
&lt;table class=&#34;gt_table&#34; data-quarto-disable-processing=&#34;false&#34; data-quarto-bootstrap=&#34;false&#34;&gt;
  &lt;thead&gt;
    &lt;tr class=&#34;gt_col_headings&#34;&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;a::stub&#34;&gt;&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;mean&#34;&gt;mean&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;sd&#34;&gt;sd&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;q0.05&#34;&gt;q0.05&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;q0.25&#34;&gt;q0.25&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;q0.5&#34;&gt;q0.5&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;q0.75&#34;&gt;q0.75&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;q0.95&#34;&gt;q0.95&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody class=&#34;gt_table_body&#34;&gt;
    &lt;tr&gt;&lt;th id=&#34;stub_1_1&#34; scope=&#34;row&#34; class=&#34;gt_row gt_left gt_stub&#34;&gt;point&lt;/th&gt;
&lt;td headers=&#34;stub_1_1 mean&#34; class=&#34;gt_row gt_right&#34;&gt;2.8&lt;/td&gt;
&lt;td headers=&#34;stub_1_1 sd&#34; class=&#34;gt_row gt_right&#34;&gt;1.5&lt;/td&gt;
&lt;td headers=&#34;stub_1_1 q0.05&#34; class=&#34;gt_row gt_right&#34;&gt;0.4&lt;/td&gt;
&lt;td headers=&#34;stub_1_1 q0.25&#34; class=&#34;gt_row gt_right&#34;&gt;1.5&lt;/td&gt;
&lt;td headers=&#34;stub_1_1 q0.5&#34; class=&#34;gt_row gt_right&#34;&gt;2.8&lt;/td&gt;
&lt;td headers=&#34;stub_1_1 q0.75&#34; class=&#34;gt_row gt_right&#34;&gt;4.1&lt;/td&gt;
&lt;td headers=&#34;stub_1_1 q0.95&#34; class=&#34;gt_row gt_right&#34;&gt;5.2&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;th id=&#34;stub_1_2&#34; scope=&#34;row&#34; class=&#34;gt_row gt_left gt_stub&#34;&gt;se&lt;/th&gt;
&lt;td headers=&#34;stub_1_2 mean&#34; class=&#34;gt_row gt_right&#34;&gt;0.3&lt;/td&gt;
&lt;td headers=&#34;stub_1_2 sd&#34; class=&#34;gt_row gt_right&#34;&gt;0.1&lt;/td&gt;
&lt;td headers=&#34;stub_1_2 q0.05&#34; class=&#34;gt_row gt_right&#34;&gt;0.2&lt;/td&gt;
&lt;td headers=&#34;stub_1_2 q0.25&#34; class=&#34;gt_row gt_right&#34;&gt;0.4&lt;/td&gt;
&lt;td headers=&#34;stub_1_2 q0.5&#34; class=&#34;gt_row gt_right&#34;&gt;0.6&lt;/td&gt;
&lt;td headers=&#34;stub_1_2 q0.75&#34; class=&#34;gt_row gt_right&#34;&gt;0.4&lt;/td&gt;
&lt;td headers=&#34;stub_1_2 q0.95&#34; class=&#34;gt_row gt_right&#34;&gt;0.3&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;th id=&#34;stub_1_3&#34; scope=&#34;row&#34; class=&#34;gt_row gt_left gt_stub&#34;&gt;ci90l&lt;/th&gt;
&lt;td headers=&#34;stub_1_3 mean&#34; class=&#34;gt_row gt_right&#34;&gt;2.2&lt;/td&gt;
&lt;td headers=&#34;stub_1_3 sd&#34; class=&#34;gt_row gt_right&#34;&gt;1.3&lt;/td&gt;
&lt;td headers=&#34;stub_1_3 q0.05&#34; class=&#34;gt_row gt_right&#34;&gt;0.2&lt;/td&gt;
&lt;td headers=&#34;stub_1_3 q0.25&#34; class=&#34;gt_row gt_right&#34;&gt;1.1&lt;/td&gt;
&lt;td headers=&#34;stub_1_3 q0.5&#34; class=&#34;gt_row gt_right&#34;&gt;1.8&lt;/td&gt;
&lt;td headers=&#34;stub_1_3 q0.75&#34; class=&#34;gt_row gt_right&#34;&gt;3.2&lt;/td&gt;
&lt;td headers=&#34;stub_1_3 q0.95&#34; class=&#34;gt_row gt_right&#34;&gt;4.7&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;th id=&#34;stub_1_4&#34; scope=&#34;row&#34; class=&#34;gt_row gt_left gt_stub&#34;&gt;ci90r&lt;/th&gt;
&lt;td headers=&#34;stub_1_4 mean&#34; class=&#34;gt_row gt_right&#34;&gt;3.4&lt;/td&gt;
&lt;td headers=&#34;stub_1_4 sd&#34; class=&#34;gt_row gt_right&#34;&gt;1.7&lt;/td&gt;
&lt;td headers=&#34;stub_1_4 q0.05&#34; class=&#34;gt_row gt_right&#34;&gt;1.1&lt;/td&gt;
&lt;td headers=&#34;stub_1_4 q0.25&#34; class=&#34;gt_row gt_right&#34;&gt;2.2&lt;/td&gt;
&lt;td headers=&#34;stub_1_4 q0.5&#34; class=&#34;gt_row gt_right&#34;&gt;3.7&lt;/td&gt;
&lt;td headers=&#34;stub_1_4 q0.75&#34; class=&#34;gt_row gt_right&#34;&gt;4.6&lt;/td&gt;
&lt;td headers=&#34;stub_1_4 q0.95&#34; class=&#34;gt_row gt_right&#34;&gt;5.6&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;th id=&#34;stub_1_5&#34; scope=&#34;row&#34; class=&#34;gt_row gt_left gt_stub&#34;&gt;ci95l&lt;/th&gt;
&lt;td headers=&#34;stub_1_5 mean&#34; class=&#34;gt_row gt_right&#34;&gt;2.1&lt;/td&gt;
&lt;td headers=&#34;stub_1_5 sd&#34; class=&#34;gt_row gt_right&#34;&gt;1.2&lt;/td&gt;
&lt;td headers=&#34;stub_1_5 q0.05&#34; class=&#34;gt_row gt_right&#34;&gt;0.2&lt;/td&gt;
&lt;td headers=&#34;stub_1_5 q0.25&#34; class=&#34;gt_row gt_right&#34;&gt;1.0&lt;/td&gt;
&lt;td headers=&#34;stub_1_5 q0.5&#34; class=&#34;gt_row gt_right&#34;&gt;1.8&lt;/td&gt;
&lt;td headers=&#34;stub_1_5 q0.75&#34; class=&#34;gt_row gt_right&#34;&gt;3.0&lt;/td&gt;
&lt;td headers=&#34;stub_1_5 q0.95&#34; class=&#34;gt_row gt_right&#34;&gt;4.6&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;th id=&#34;stub_1_6&#34; scope=&#34;row&#34; class=&#34;gt_row gt_left gt_stub&#34;&gt;ci95r&lt;/th&gt;
&lt;td headers=&#34;stub_1_6 mean&#34; class=&#34;gt_row gt_right&#34;&gt;3.5&lt;/td&gt;
&lt;td headers=&#34;stub_1_6 sd&#34; class=&#34;gt_row gt_right&#34;&gt;1.7&lt;/td&gt;
&lt;td headers=&#34;stub_1_6 q0.05&#34; class=&#34;gt_row gt_right&#34;&gt;1.1&lt;/td&gt;
&lt;td headers=&#34;stub_1_6 q0.25&#34; class=&#34;gt_row gt_right&#34;&gt;2.5&lt;/td&gt;
&lt;td headers=&#34;stub_1_6 q0.5&#34; class=&#34;gt_row gt_right&#34;&gt;3.8&lt;/td&gt;
&lt;td headers=&#34;stub_1_6 q0.75&#34; class=&#34;gt_row gt_right&#34;&gt;4.7&lt;/td&gt;
&lt;td headers=&#34;stub_1_6 q0.95&#34; class=&#34;gt_row gt_right&#34;&gt;5.7&lt;/td&gt;&lt;/tr&gt;
  &lt;/tbody&gt;
  
  
&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Interested readers can find more real data examples in &lt;a href=&#34;https://doi.org/10.1371/journal.pcbi.1013338&#34;&gt;Gressani and Hens (2025)&lt;/a&gt; and learn about the strengths and limitations of this new nonparametric methodology for serial interval estimation.&lt;/p&gt;
&lt;div id=&#34;references&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;References&lt;/h3&gt;
&lt;p&gt;Gressani, O. and Hens, N. (2025). Nonparametric serial interval estimation with uniform mixtures.
&lt;em&gt;PLoS Computational Biology&lt;/em&gt; &lt;strong&gt;21&lt;/strong&gt;(8):e101338. &lt;a href=&#34;https://doi.org/10.1371/journal.pcbi.1013338&#34; class=&#34;uri&#34;&gt;https://doi.org/10.1371/journal.pcbi.1013338&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Gressani; O. (2025). EpiDelays: A Software for Estimation of Epidemiological Delays (version 0.0.1). &lt;a href=&#34;https://github.com/oswaldogressani/EpiDelays&#34; class=&#34;uri&#34;&gt;https://github.com/oswaldogressani/EpiDelays&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Lessler, J., Reich, N. G., Cummings, D. A., and the New York City Department of Health and Mental Hygiene Swine Influenza Investigation Team. (2009). Outbreak of 2009 pandemic influenza A (H1N1) at a New York City school. &lt;em&gt;New England Journal of Medicine&lt;/em&gt; &lt;strong&gt;361&lt;/strong&gt;(27), 2628-2636. &lt;a href=&#34;https://www.nejm.org/doi/full/10.1056/NEJMoa0906089&#34; class=&#34;uri&#34;&gt;https://www.nejm.org/doi/full/10.1056/NEJMoa0906089&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Paper: &#39;Semi-Markov modeling for disease incidence risk and duration&#39;</title>
      <link>https://statsandr.com/blog/paper-semi-markov-modeling-for-disease-incidence-risk-and-duration/</link>
      <pubDate>Mon, 16 Jun 2025 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/paper-semi-markov-modeling-for-disease-incidence-risk-and-duration/</guid>
      <description>


&lt;p&gt;&lt;img src=&#34;images/paper-semi-markov-modeling-for-disease-incidence-risk-and-duration.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;I’m happy to share that my latest research paper, &lt;em&gt;“Semi-Markov modeling for disease incidence risk and duration”&lt;/em&gt; has been accepted for publication in the journal Biostatistics &amp;amp; Epidemiology &lt;a href=&#34;https://doi.org/10.1080/24709360.2025.2517916&#34;&gt;(Soetewey et al., 2025)&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Read the full paper &lt;a href=&#34;https://doi.org/10.1080/24709360.2025.2517916&#34;&gt;here&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;This work focuses on the use of a &lt;strong&gt;Semi-Markov illness-death model&lt;/strong&gt; to estimate both:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The risk of cancer incidence&lt;/strong&gt; over a future time period&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The number of years of life lost (YLL)&lt;/strong&gt; due to cancer, with a focus on loss before age 70&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The analysis relies on real-world data from the &lt;strong&gt;Belgian Cancer Registry&lt;/strong&gt;, covering over 160,000 cases of melanoma, thyroid, and female breast cancer diagnosed between 2004 and 2020. By modeling transitions between “healthy,” “ill,” and “dead” states, we provide a comprehensive framework to better understand disease burden over time, not just at diagnosis, but also for long-term survivors.&lt;/p&gt;
&lt;p&gt;One key feature of this work is its application to &lt;strong&gt;non-homogeneous Semi-Markov processes&lt;/strong&gt;, allowing us to account for the time since diagnosis when estimating survival and life expectancy. This adds a clinically meaningful dynamic dimension to traditional multi-state models.&lt;/p&gt;
&lt;p&gt;Beyond its methodological contributions, this study has important implications for &lt;strong&gt;public health&lt;/strong&gt; and &lt;strong&gt;insurance regulation&lt;/strong&gt;. In particular, the results offer quantitative support for the &lt;strong&gt;right to be forgotten&lt;/strong&gt;; a legal provision that allows cancer survivors to apply for credit or insurance products without being penalized once they’ve reached a certain number of years since the end of treatment.&lt;/p&gt;
&lt;p&gt;Our results suggest that, for many patients who survive 10 years post-diagnosis, the expected loss in life years compared to the general population becomes minimal, sometimes even below one year. This is especially true for cancers like melanoma and thyroid cancer. These findings could contribute to more equitable and evidence-based insurance underwriting practices.&lt;/p&gt;
&lt;p&gt;This research was a collaborative effort, and I would like to express my sincere thanks to my former PhD supervisors, Catherine Legrand, Michel Denuit (UCLouvain) and Geert Silversmit (Belgian Cancer Registry), for their invaluable guidance and support throughout the project.&lt;/p&gt;
&lt;p&gt;Thanks for reading!&lt;/p&gt;
&lt;div id=&#34;references&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;References&lt;/h2&gt;
&lt;p&gt;Soetewey, A., Legrand, C., Denuit, M., &amp;amp; Silversmit, G. (2025). Semi-Markov modeling for disease incidence risk and duration. &lt;em&gt;Biostatistics &amp;amp; Epidemiology, 9&lt;/em&gt;(1). &lt;a href=&#34;https://doi.org/10.1080/24709360.2025.2517916&#34; class=&#34;uri&#34;&gt;https://doi.org/10.1080/24709360.2025.2517916&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Paper: &#39;Right to be forgotten for mortgage insurance issued to cancer survivors: critical assessment and new proposal&#39;</title>
      <link>https://statsandr.com/blog/paper-right-to-be-forgotten-for-mortgage-insurance-issued-to-cancer-survivors-critical-assessment-and-new-proposal/</link>
      <pubDate>Tue, 05 Nov 2024 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/paper-right-to-be-forgotten-for-mortgage-insurance-issued-to-cancer-survivors-critical-assessment-and-new-proposal/</guid>
      <description>


&lt;p&gt;&lt;img src=&#34;images/paper-right-to-be-forgotten-for-mortgage-insurance-issued-to-cancer-survivors-critical-assessment-and-new-proposal.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;I am happy to announce that our paper entitled “Right to be forgotten for mortgage insurance issued to cancer survivors: critical assessment and new proposal” has been accepted for publication in &lt;em&gt;European Actuarial Journal&lt;/em&gt; &lt;a href=&#34;https://doi.org/10.1007/s13385-024-00403-6&#34;&gt;(Soetewey et al., 2025)&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;In this paper, we propose an alternative method to determine the waiting period opening the right to be forgotten in insurance. This new method is based on a constraint imposed to the premium, which is then transposed into a target on the conditional observed survival. Furthermore, the paper also investigates the impact of the stage of the tumor at diagnosis on waiting periods.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Read more &lt;a href=&#34;http://dx.doi.org/10.1007/s13385-024-00403-6&#34;&gt;here&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Thanks to all co-authors for the great work. We are also thankful to the two anonymous reviewers for their input that has greatly helped shape the paper.&lt;/p&gt;
&lt;p&gt;As always, if you have any question related to the topic covered in this paper, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;div id=&#34;references&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;References&lt;/h2&gt;
&lt;p&gt;Soetewey, A., Legrand, C., Denuit, M. et al. Right to be forgotten for mortgage insurance issued to cancer survivors: critical assessment and new proposal. &lt;em&gt;European Actuarial Journal&lt;/em&gt; &lt;strong&gt;15&lt;/strong&gt;, 15–43 (2025). &lt;a href=&#34;https://doi.org/10.1007/s13385-024-00403-6&#34; class=&#34;uri&#34;&gt;https://doi.org/10.1007/s13385-024-00403-6&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>EpiLPS for estimation of incubation times</title>
      <link>https://statsandr.com/blog/epilps-for-estimation-of-incubation-times/</link>
      <pubDate>Thu, 01 Aug 2024 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/epilps-for-estimation-of-incubation-times/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#motivation&#34; id=&#34;toc-motivation&#34;&gt;Motivation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#coarse-data&#34; id=&#34;toc-coarse-data&#34;&gt;Coarse data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#simulated-example&#34; id=&#34;toc-simulated-example&#34;&gt;Simulated example&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#real-data-example&#34; id=&#34;toc-real-data-example&#34;&gt;Real data example&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;div id=&#34;motivation&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Motivation&lt;/h1&gt;
&lt;p&gt;A group of researchers from the Data Science Institute (DSI) at Hasselt University developed a new statistical model to estimate the incubation period of a pathogenic organism based on coarse data. The incubation period of an infectious disease (defined as the time elapsed between infection and the manifestation of first symptoms) is of great importance as it permits to shed light on the epidemic potential of a disease and to optimize the length of quarantine periods to freeze transmission. The article &lt;a href=&#34;https://doi.org/10.1093/aje/kwae192&#34;&gt;(Gressani et al. 2024)&lt;/a&gt; was recently published in the &lt;em&gt;American Journal of Epidemiology&lt;/em&gt; with practical implementation of the methodology accessible through the &lt;a href=&#34;https://statsandr.com/blog/paper-epilps-a-fast-and-flexible-bayesian-tool-for-estimation-of-the-time-varying-reproduction-number/&#34;&gt;EpiLPS package&lt;/a&gt; &lt;a href=&#34;https://doi.org/10.1371/journal.pcbi.1010618&#34;&gt;(Gressani et al. 2022)&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;coarse-data&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Coarse data&lt;/h1&gt;
&lt;p&gt;What makes estimation of incubation times so challenging in the first place? The devil lies in the data. True infection times are stealthy and rarely observed. In information-theoretic jargon this phenomenon is called “imperfect information’’ but statisticians prefer to call it censoring. To be more precise, infection times are interval censored, i.e. one part of the collected data contains exposure intervals &lt;span class=&#34;math inline&#34;&gt;\(\mathcal{E}=[t^{E_L},t^{E_R}]\)&lt;/span&gt; reported by individuals that are part of the study, where &lt;span class=&#34;math inline&#34;&gt;\(t^{E_L}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(t^{E_R}\)&lt;/span&gt; stand for the left and right bound, respectively, of the exposure window. The other part of the data contains symptom onset times &lt;span class=&#34;math inline&#34;&gt;\(t^{\mathcal{S}}\)&lt;/span&gt;. This is a more easily accessible piece of information -people tend to remember the day when first symptoms appeared- and so the timing of symptom onset is assumed to be exactly observed. Subtracting the exposure bounds from the symptom onset time, one obtains the incubation interval &lt;span class=&#34;math inline&#34;&gt;\(\mathcal{I}=[t^{\mathcal{I}_L}, t^{\mathcal{I}_R}]\)&lt;/span&gt; with lower bound &lt;span class=&#34;math inline&#34;&gt;\(t^{\mathcal{I}_L}=t^{\mathcal{S}}-t^{E_R}\)&lt;/span&gt; and upper bound &lt;span class=&#34;math inline&#34;&gt;\(t^{\mathcal{I}_R}=t^{\mathcal{S}}-t^{E_L}\)&lt;/span&gt;, characterizing the coarse data structure which will be the main model input.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;simulated-example&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Simulated example&lt;/h1&gt;
&lt;p&gt;In EpiLPS, the &lt;code&gt;estimIncub()&lt;/code&gt; routine is designed to compute an estimate of the incubation density based on the methodology of &lt;a href=&#34;https://doi.org/10.1093/aje/kwae192&#34;&gt;Gressani et al. (2024)&lt;/a&gt;. Giving a detailed account of the methodology would be out of scope for this blog and the reader is redirected to the article for technicalities. In a nutshell, it is a Bayesian approach making use of (penalized) B-splines, Laplace approximations and Markov chain Monte Carlo (MCMC) methods to derive a semi-parametric estimate of the incubation density. An attractive feature of the &lt;code&gt;estimIncub()&lt;/code&gt; routine for the end-user is the minimalistic input it requires to work, namely:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;x&lt;/code&gt;: A data frame containing the lower and upper bound of the incubation interval.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;K&lt;/code&gt;: An integer specifying the number of B-splines to smooth the incubation density.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;niter&lt;/code&gt;: The number of MCMC samples required.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In practice, only the data frame &lt;code&gt;x&lt;/code&gt; is required as the remaining inputs are assigned default values. Computationally, the routine requires a small amount of resources as costly subroutines are coded in C++ and integrated in R via the Rcpp package. The structure of &lt;code&gt;x&lt;/code&gt; is quite simple. It should be a data frame with two columns containing the left bound &lt;span class=&#34;math inline&#34;&gt;\(t^{\mathcal{I}_L}\)&lt;/span&gt; of the incubation interval (in the first column) and the right bound &lt;span class=&#34;math inline&#34;&gt;\(t^{\mathcal{I}_R}\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Let’s start with a simple example where &lt;code&gt;x&lt;/code&gt; is simulated based on a data generating mechanism assuming a known incubation distribution. This can be achieved with the &lt;code&gt;incubsim()&lt;/code&gt; routine in EpiLPS. We choose &lt;code&gt;x&lt;/code&gt; to be generated according to a Lognormal incubation distribution with a mean of 5.5 days and a standard deviation of 2.1 days following &lt;a href=&#34;https://doi.org/10.1126/science.abb6936&#34;&gt;Ferretti et al. (2020)&lt;/a&gt;. Simulation of &lt;span class=&#34;math inline&#34;&gt;\(n=40\)&lt;/span&gt; observations with an average exposure window of 2 days is implemented as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(2024)
simdat &amp;lt;- incubsim(incubdist = &amp;quot;LogNormal&amp;quot;, n = 40, coarseness = 2)
gt(head(simdat$Dobsincub, 5))&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;kocanygkly&#34; style=&#34;padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;&#34;&gt;
&lt;style&gt;#kocanygkly table {
  font-family: system-ui, &#39;Segoe UI&#39;, Roboto, Helvetica, Arial, sans-serif, &#39;Apple Color Emoji&#39;, &#39;Segoe UI Emoji&#39;, &#39;Segoe UI Symbol&#39;, &#39;Noto Color Emoji&#39;;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

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

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

#kocanygkly .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;
}

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

#kocanygkly .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;
}

#kocanygkly .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;
}

#kocanygkly .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;
}

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

#kocanygkly .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;
}

#kocanygkly .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;
}

#kocanygkly .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;
}

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

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

#kocanygkly .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%;
}

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

#kocanygkly .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;
}

#kocanygkly .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;
}

#kocanygkly .gt_from_md &gt; :first-child {
  margin-top: 0;
}

#kocanygkly .gt_from_md &gt; :last-child {
  margin-bottom: 0;
}

#kocanygkly .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;
}

#kocanygkly .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;
}

#kocanygkly .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;
}

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

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

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

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

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

#kocanygkly .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;
}

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

#kocanygkly .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;
}

#kocanygkly .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;
}

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

#kocanygkly .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;
}

#kocanygkly .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;
}

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

#kocanygkly .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;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#kocanygkly .gt_indent_5 {
  text-indent: 25px;
}
&lt;/style&gt;
&lt;table class=&#34;gt_table&#34; data-quarto-disable-processing=&#34;false&#34; data-quarto-bootstrap=&#34;false&#34;&gt;
  &lt;thead&gt;
    &lt;tr class=&#34;gt_col_headings&#34;&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;tL&#34;&gt;tL&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;tR&#34;&gt;tR&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody class=&#34;gt_table_body&#34;&gt;
    &lt;tr&gt;&lt;td headers=&#34;tL&#34; class=&#34;gt_row gt_right&#34;&gt;3.724500&lt;/td&gt;
&lt;td headers=&#34;tR&#34; class=&#34;gt_row gt_right&#34;&gt;5.510304&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;tL&#34; class=&#34;gt_row gt_right&#34;&gt;4.381377&lt;/td&gt;
&lt;td headers=&#34;tR&#34; class=&#34;gt_row gt_right&#34;&gt;6.654224&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;tL&#34; class=&#34;gt_row gt_right&#34;&gt;4.588020&lt;/td&gt;
&lt;td headers=&#34;tR&#34; class=&#34;gt_row gt_right&#34;&gt;5.483614&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;tL&#34; class=&#34;gt_row gt_right&#34;&gt;3.847835&lt;/td&gt;
&lt;td headers=&#34;tR&#34; class=&#34;gt_row gt_right&#34;&gt;6.003948&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;tL&#34; class=&#34;gt_row gt_right&#34;&gt;3.522282&lt;/td&gt;
&lt;td headers=&#34;tR&#34; class=&#34;gt_row gt_right&#34;&gt;5.033487&lt;/td&gt;&lt;/tr&gt;
  &lt;/tbody&gt;
  
  
&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;By typing &lt;code&gt;simdat$Dobsincub&lt;/code&gt;, the user has access to the generated incubation intervals (expressed in days), corresponding here to a data frame with two columns and &lt;span class=&#34;math inline&#34;&gt;\(n=40\)&lt;/span&gt; rows. This is the data frame that is injected in the &lt;code&gt;estimIncub()&lt;/code&gt; routine:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;fit &amp;lt;- estimIncub(x = simdat$Dobsincub, verbose = TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## ----------------------------------------------------------------
## Time elapsed: 1.339 seconds.
## Fitted density is Log-Normal with meanlog=1.617 and sdlog=0.317.
## Mean incubation period (days): 5.298 with 95% CI: 5.086-5.615.
## 95th percentile (days): 8.484 with 95% CI: 8.121-9.089.
## ----------------------------------------------------------------&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output in the R console can easily be interpreted. It tells us that the model chooses a Lognormal density fit for the incubation period with a mean of 5.3 days (95% CI: 5.0-5.6 days). More detailed summary statistics are accessible by typing &lt;code&gt;fit$stats&lt;/code&gt;, such as the posterior standard deviation and additional percentiles. What happens under the hood? Basically, the model computes a semi-parametric fit to the data and compares it with classic parametric fits (Lognormal, Weibull and Gamma) used for incubation modeling. The candidate with the lowest Bayesian information criterion (BIC) wins the game and is finally selected (here the Lognormal distribution). The incubation windows and the fitted incubation density can be obtained by typing:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;grid.arrange(plot(fit, typ = &amp;quot;incubwin&amp;quot;), plot(fit, type = &amp;quot;pdf&amp;quot;), nrow = 1)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/epilps-for-estimation-of-incubation-times/index_files/figure-html/estimincubation-2-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;real-data-example&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Real data example&lt;/h1&gt;
&lt;p&gt;The flexible Bayesian methodology is illustrated on SARS-CoV-2 symptom onset and exposure window data extracted from cases in Vietnam. The dataset was analyzed in &lt;a href=&#34;https://doi.org/10.1371/journal.pone.0243889&#34;&gt;Bui et al. (2020)&lt;/a&gt; and is publicly available on the GitHub repository provided in the article (&lt;a href=&#34;https://github.com/longbui/Covid19IncubVN&#34; class=&#34;uri&#34;&gt;https://github.com/longbui/Covid19IncubVN&lt;/a&gt;; last accessed July 17, 2024). The dataset contains information about &lt;span class=&#34;math inline&#34;&gt;\(n=19\)&lt;/span&gt; cases identified from January 23, 2020 to April 13, 2020. After continuity corrections (required to change calendar dates into continuous time points), the left and right incubation bounds are given by:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Left incubation bound
tL &amp;lt;- c(0.504, 2.983, 5.343, 6.969, 6.990, 2.570, 6.870, 1.263, 0.693, 1.869, 1.151, 2.748, 1.209, 1.161, 4.982, 4.017, 2.170, 9.805, 1.659)

# Right incubation bound
tR &amp;lt;- c(1.491, 7.762, 11.777, 12.821, 11.359, 8.551, 24.954, 4.144, 6.408, 7.083, 4.191, 10.326, 9.942, 7.254, 12.690, 10.825, 14.478, 16.592, 18.649)

# Data set
dataVietnam &amp;lt;- data.frame(tL = tL, tR = tR)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;estimIncub()&lt;/code&gt; routine provides a Weibull fit with a mean incubation period of 6.7 days (95% CI: 5.8-7.4 days) and the standard deviation (extracted by typing &lt;code&gt;incubfit$stats&lt;/code&gt;) is 3.3 days (95% CI: 3.0-3.8 days). A figure of the incubation windows and the fitted Weibull density (with 95% credible interval) is also provided.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(2024)
incubfit &amp;lt;- EpiLPS::estimIncub(x = dataVietnam, verbose = TRUE, tmax = 25)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## ----------------------------------------------------------------
## Time elapsed: 1.13 seconds.
## Fitted density is Weibull with shape=2.142 and scale=7.521.
## Mean incubation period (days): 6.661 with 95% CI: 5.753-7.375.
## 95th percentile (days): 12.552 with 95% CI: 11.931-14.087.
## ----------------------------------------------------------------&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;grid.arrange(plot(incubfit, typ = &amp;quot;incubwin&amp;quot;), plot(incubfit, type = &amp;quot;pdf&amp;quot;), nrow = 1)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/epilps-for-estimation-of-incubation-times/index_files/figure-html/RealData-3-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;p&gt;Gressani, O., Torneri, A., Hens, N. and Faes, C. (2024). Flexible Bayesian estimation of incubation times. &lt;em&gt;American Journal of Epidemiology&lt;/em&gt; (Accepted manuscript). &lt;a href=&#34;https://doi.org/10.1093/aje/kwae192&#34; class=&#34;uri&#34;&gt;https://doi.org/10.1093/aje/kwae192&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Gressani, O., Wallinga, J., Althaus, C. L., Hens, N. and Faes, C.
(2022). EpiLPS: A fast and flexible Bayesian tool for estimation of the
time-varying reproduction number. &lt;em&gt;PLoS Comput Biol&lt;/em&gt; &lt;strong&gt;18&lt;/strong&gt;(10):
e1010618. &lt;a href=&#34;https://doi.org/10.1371/journal.pcbi.1010618&#34; class=&#34;uri&#34;&gt;https://doi.org/10.1371/journal.pcbi.1010618&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Eddelbuettel, D. and Francois, R. (2011). Rcpp: Seamless R and C++ Integration. &lt;em&gt;Journal of Statistical Software&lt;/em&gt;, &lt;strong&gt;40&lt;/strong&gt;(8), 1–18. &lt;a href=&#34;https://doi.org/10.18637/jss.v040.i08&#34; class=&#34;uri&#34;&gt;https://doi.org/10.18637/jss.v040.i08&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Ferretti, L. et al. (2020). Quantifying SARS-CoV-2 transmission suggests epidemic control with
digital contact tracing. &lt;em&gt;Science&lt;/em&gt; &lt;strong&gt;368&lt;/strong&gt;, eabb6936. &lt;a href=&#34;https://doi.org/10.1126/science.abb6936&#34; class=&#34;uri&#34;&gt;https://doi.org/10.1126/science.abb6936&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Bui LV, Nguyen HT, Levine H, Nguyen HN, Nguyen T-A, Nguyen TP, et al. (2020) Estimation of the incubation period of COVID-19 in Vietnam. &lt;em&gt;PLoS ONE&lt;/em&gt; &lt;strong&gt;15&lt;/strong&gt;(12): e0243889. &lt;a href=&#34;https://doi.org/10.1371/journal.pone.0243889&#34; class=&#34;uri&#34;&gt;https://doi.org/10.1371/journal.pone.0243889&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Binary logistic regression in R</title>
      <link>https://statsandr.com/blog/binary-logistic-regression-in-r/</link>
      <pubDate>Tue, 30 Jan 2024 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/binary-logistic-regression-in-r/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#linear-versus-logistic-regression&#34; id=&#34;toc-linear-versus-logistic-regression&#34;&gt;Linear versus logistic regression&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#univariable-versus-multivariable-logistic-regression&#34; id=&#34;toc-univariable-versus-multivariable-logistic-regression&#34;&gt;Univariable versus multivariable logistic regression&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#data&#34; id=&#34;toc-data&#34;&gt;Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#binary-logistic-regression-in-r&#34; id=&#34;toc-binary-logistic-regression-in-r&#34;&gt;Binary logistic regression in R&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#univariable-binary-logistic-regression&#34; id=&#34;toc-univariable-binary-logistic-regression&#34;&gt;Univariable binary logistic regression&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#quantitative-independent-variable&#34; id=&#34;toc-quantitative-independent-variable&#34;&gt;Quantitative independent variable&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#qualitative-independent-variable&#34; id=&#34;toc-qualitative-independent-variable&#34;&gt;Qualitative independent variable&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#multivariable-binary-logistic-regression&#34; id=&#34;toc-multivariable-binary-logistic-regression&#34;&gt;Multivariable binary logistic regression&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#interaction&#34; id=&#34;toc-interaction&#34;&gt;Interaction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#model-selection&#34; id=&#34;toc-model-selection&#34;&gt;Model selection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#quality-of-a-model&#34; id=&#34;toc-quality-of-a-model&#34;&gt;Quality of a model&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#validity-of-the-predictions&#34; id=&#34;toc-validity-of-the-predictions&#34;&gt;Validity of the predictions&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#accuracy&#34; id=&#34;toc-accuracy&#34;&gt;Accuracy&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#sensitivity-and-specificity&#34; id=&#34;toc-sensitivity-and-specificity&#34;&gt;Sensitivity and specificity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#auc-and-roc-curve&#34; id=&#34;toc-auc-and-roc-curve&#34;&gt;AUC and ROC curve&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#reporting-results&#34; id=&#34;toc-reporting-results&#34;&gt;Reporting results&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#gtsummary-package&#34; id=&#34;toc-gtsummary-package&#34;&gt;{gtsummary} package&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#finalfit-package&#34; id=&#34;toc-finalfit-package&#34;&gt;{finalfit} package&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conditions-of-application&#34; id=&#34;toc-conditions-of-application&#34;&gt;Conditions of application&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;images/binary-logistic-regression-in-r.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;Regression is a common tool in statistics to test and quantify relationships between variables.&lt;/p&gt;
&lt;p&gt;The two most common regressions are linear and logistic regressions. A &lt;strong&gt;linear&lt;/strong&gt; regression is used when the dependent variable is &lt;strong&gt;quantitative&lt;/strong&gt;, whereas a &lt;strong&gt;logistic&lt;/strong&gt; regression is used when the dependent variable is &lt;strong&gt;qualitative&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Both linear and logistic regressions are divided into different types. Before detailing them, let’s first recap of which type a variable can be:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A quantitative variable measures a quantity, the values it can take are numbers. It is divided into:
&lt;ul&gt;
&lt;li&gt;discrete: the values it can take are countable and have a finite number of possibilities (the values are often integers, for example the number of children), and&lt;/li&gt;
&lt;li&gt;continuous: the values it can take are not countable and have an infinite number of possibilities (the values are usually with decimals, or at least decimals are technically possible, for example the weight).&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;A qualitative variable (also known as categorical) is not numerical and its values fit into categories. It is also divided into two types:
&lt;ul&gt;
&lt;li&gt;nominal: no ordering is possible or implied in the categories (for example the sex), and&lt;/li&gt;
&lt;li&gt;ordinal: an order is implied in the categories (for example the health status, such as poor/reasonable/good).&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A &lt;strong&gt;binary&lt;/strong&gt; variable, also known as dichotomous, is a special case of qualitative nominal variable when there are &lt;strong&gt;only two categories&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;See more details and examples about &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/&#34;&gt;variable types&lt;/a&gt; if needed.&lt;/p&gt;
&lt;p&gt;Now that the types of a variable is clear, let’s summarize the different types of regression:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Linear regression:
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Simple&lt;/strong&gt; linear regression is used when the goal is to estimate the relationship between a quantitative continuous dependent variable (also often called outcome or response variable) and &lt;strong&gt;only one&lt;/strong&gt; independent variable (also often called explanatory variable, covariate or predictor) of any type.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Multiple&lt;/strong&gt; linear regression is used when the goal is to estimate the relationship between a quantitative continuous dependent variable and &lt;strong&gt;two or more&lt;/strong&gt; independent variables (again, of any type).&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Logistic regression:
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Binary&lt;/strong&gt; logistic regression is used when the goal is to estimate the relationship between a &lt;strong&gt;binary dependent variable&lt;/strong&gt; (= two outcomes), and one or more independent variables (of any type).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Multinomial&lt;/strong&gt; logistic regression is used when the goal is to estimate the relationship between a &lt;strong&gt;nominal dependent variable&lt;/strong&gt; with three or more &lt;em&gt;unordered&lt;/em&gt; outcomes, and one or more independent variables (of any type).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Ordinal&lt;/strong&gt; logistic regression is used when the goal is to estimate the relationship between an &lt;strong&gt;ordinal dependent variable&lt;/strong&gt; with three or more &lt;em&gt;ordered&lt;/em&gt; outcomes, and one or more independent variables (of any type).&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that there exists another type of regression; the Poisson regression. This type of regression is used when the goal is to estimate the relationship between a dependent variable which is in the form of count data (number of occurrences of an event of interest over a given period of time or space, e.g., &lt;span class=&#34;math inline&#34;&gt;\(0, 1, 2, \ldots\)&lt;/span&gt;), and one or more independent variables.&lt;/p&gt;
&lt;p&gt;Logistic regressions and poisson regressions are both part of a broader type of model called &lt;strong&gt;generalized linear models&lt;/strong&gt; (abbreviated as &lt;strong&gt;GLM&lt;/strong&gt;). The name “generalized linear models” comes from the fact that these models allow to “generalize” the classic linear model. Indeed, it can be used in many situations, for example when analyzing a dependent variable which is not necessarily quantitative continuous or when residuals are not normally distributed (which are prerequisites for a linear model).&lt;/p&gt;
&lt;p&gt;Linear regression and its application in R have already been presented in this &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;post&lt;/a&gt;. It is now time to present the logistic regression.&lt;/p&gt;
&lt;p&gt;Binary logistic regression being the most common and the easiest one to interpret among the different types of logistic regression, this post will focus only on the binary logistic regression. Other types of regression (multinomial &amp;amp; ordinal logistic regressions, as well as Poisson regressions are left for future posts).&lt;/p&gt;
&lt;p&gt;In this post, we will first explain when a logistic regression is more appropriate than a linear regression. We will then show how to perform a binary logistic regression in R, and how to interpret and report results. We will also present some plots in order to visualize results. Finally, we will cover the topics of model selection, quality of fit and underlying assumptions of a binary logistic regression. We will try to keep this tutorial as applied as possible by focusing on the applications in R and the interpretations. Mathematical details will be as concise as possible.&lt;/p&gt;
&lt;div id=&#34;linear-versus-logistic-regression&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Linear versus logistic regression&lt;/h2&gt;
&lt;p&gt;We know that a linear regression is a convenient way to estimate the relationship between a quantitative continuous dependent variable, and one or more independent variables (of any type).&lt;/p&gt;
&lt;p&gt;For instance, suppose we would like to estimate the relationship between two quantitative variables, &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt;. Using the ordinary least squares method (the most common estimator used in linear regression), we obtain the following regression line:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/index_files/figure-html/unnamed-chunk-1-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Now suppose we are interested in estimating the impact of age on whether or not a patient has a certain disease. Age is considered as a quantitative continuous variable, while having the disease is binary (a patient is either ill or healthy).&lt;/p&gt;
&lt;p&gt;Visually, we could have something like this:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/index_files/figure-html/unnamed-chunk-2-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;If we fit a regression line (using the ordinary least square method) to the points, we obtain the following plot:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/index_files/figure-html/unnamed-chunk-3-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;We see that the regression line goes below 0 and above 1 with respect to the &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt;-axis. Since the dependent variable &lt;code&gt;disease&lt;/code&gt; cannot take values below 0 (= healthy) nor above 1 (= ill), it is obvious that a linear regression is not appropriate for these data!&lt;/p&gt;
&lt;p&gt;In addition to this limitation, the assumptions of normality and homoscedasticity, which are required in linear regression, are clearly not appropriate with these data since the dependent variable is binary and follows a Binomial distribution! R will not stop you from performing a linear regression on binary data, but this will produce a model of little interest.&lt;/p&gt;
&lt;p&gt;This is where a logistic regression becomes handy as it takes into consideration these limitations.&lt;/p&gt;
&lt;p&gt;Applied to our example, here is how the points are fitted using a binary logistic regression:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/index_files/figure-html/unnamed-chunk-4-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;It is clear that this model is more appropriate.&lt;/p&gt;
&lt;p&gt;The curve (known as a sigmoid) is obtained via a transformation of the predicted values. There are several possible choices for the link function, which aim is to constrain predicted values to be within the range of observed values.&lt;/p&gt;
&lt;p&gt;The most widely used in practice is the logit function, which relates the probability of occurrence of an event (bounded between 0 and 1) to the linear combination of independent variables. The logit function also turns out to be the canonical link function for a Bernoulli or Binomial distribution. This transformation ensures that no matter in which range the &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; values are located, &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; will only take numbers between 0 and 1.&lt;/p&gt;
&lt;p&gt;One could say that the fitted values (= represented by the blue curve) taking values between 0 and 1 also does not seem to make sense since a patient can only be healthy or ill (and thus the dependent variable can only take the value 0 or 1, respectively). However, in a binary logistic regression it is not the outcome no disease/disease that is directly modeled, but the &lt;em&gt;likelihood&lt;/em&gt; that a patient has the disease or not given his or her characteristics. This likelihood will be framed in terms of a &lt;a href=&#34;https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/&#34;&gt;probability&lt;/a&gt; to observe or not the disease in a patient, which is indeed included between 0 and 1, or 0% and 100%.&lt;/p&gt;
&lt;p&gt;More generally, with a logistic regression we would like to &lt;strong&gt;model how the probability of success varies with the independent variables&lt;/strong&gt; and determine whether or not these changes are statistically significant. We are actually going to model the logarithm of the odds, and the logistic regression model will be written as follows:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
\log(odds(success)) &amp;amp;= logit(\pi) \\
&amp;amp;= \log\left(\frac{\pi}{1 - \pi}\right) \\
&amp;amp;= \beta_0 + \beta_1 X_1 + \cdots + \beta_p X_p
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(\pi\)&lt;/span&gt; &lt;span class=&#34;math inline&#34;&gt;\((0 \le \pi \le 1)\)&lt;/span&gt; is the probability of an event happening (success) and denoted &lt;span class=&#34;math inline&#34;&gt;\(\pi = P(success)\)&lt;/span&gt;. We find the values of &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_0\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_1\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(\ldots\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_p\)&lt;/span&gt;, which are used as estimates for &lt;span class=&#34;math inline&#34;&gt;\(\beta_0\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(\beta_1\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(\ldots\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(\beta_p\)&lt;/span&gt;, using the maximum likelihood method. This method is one of several methods used in statistics to estimate parameters of a mathematical model. The goal of the estimator is to estimate the parameters &lt;span class=&#34;math inline&#34;&gt;\(\beta_0\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(\beta_1\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(\ldots\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(\beta_p\)&lt;/span&gt; which maximize the log likelihood function. Different algorithms have been established over the years for this non-linear optimization, but this is beyond the scope of the post.&lt;/p&gt;
&lt;p&gt;Logistic regressions are very common in the medical field, for example to:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;estimate the risk factors associated with a disease or a harmful condition,&lt;/li&gt;
&lt;li&gt;predict the risk of developing a disease based on a patient’s characteristics, or&lt;/li&gt;
&lt;li&gt;determine the most important biological factors associated with a specific disease or condition.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;However, logistic regressions are used in many other domains, for instance in:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;banking sector: estimate a debtor’s creditworthiness based on his or her profile (income, assets, liabilities, etc.),&lt;/li&gt;
&lt;li&gt;marketing: estimate a customer’s propensity to buy a product or service based on his or her profile (age, sex, salary, previous purchases, etc.),&lt;/li&gt;
&lt;li&gt;sports: estimate the probability of a player winning against another player as a function of the characteristics of the two opponents,&lt;/li&gt;
&lt;li&gt;politics: answer the question “Would a citizen vote for our political party at the next elections?”&lt;/li&gt;
&lt;li&gt;etc.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;univariable-versus-multivariable-logistic-regression&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Univariable versus multivariable logistic regression&lt;/h2&gt;
&lt;p&gt;Now that it is more clear when a binary logistic regression should be used, we show how to perform one in R. We start by presenting univariable binary logistic regressions, and then multivariable binary logistic regressions.&lt;/p&gt;
&lt;p&gt;Remember that in both cases, the dependent variable must be a qualitative variable with two outcomes (hence the name &lt;em&gt;binary&lt;/em&gt; logistic regression). The difference between a univariable and multivariable binary logistic regression lies in the fact that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;for a &lt;strong&gt;univariable&lt;/strong&gt; binary logistic regression, there is only &lt;strong&gt;one independent variable&lt;/strong&gt;, while&lt;/li&gt;
&lt;li&gt;for a &lt;strong&gt;multivariable&lt;/strong&gt; binary logistic regression, there are &lt;strong&gt;two ore more independent variables&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;It is true that the term “univariable” may be confusing here because there are two variables in the model (i.e., one dependent variable and one independent variable). However, it is called univariable binary logistic regression to indicate that only one independent variable is considered in the model, as opposed to multivariable binary logistic regression where several independent variables are considered in the model.&lt;/p&gt;
&lt;p&gt;To draw a parallel with linear regression:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a univariable binary logistic regression is the equivalent of a simple linear regression, whereas&lt;/li&gt;
&lt;li&gt;a multivariable binary logistic regression is the equivalent of a multiple linear regression&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;when the dependent variable is binary instead of quantitative continuous. This is the reason a univariable binary logistic regression is sometimes called a simple binary logistic regression and a multivariable binary logistic regression sometimes called a multiple binary logistic regression.&lt;/p&gt;
&lt;p&gt;The terms univaria&lt;em&gt;ble&lt;/em&gt;/multivaria&lt;em&gt;ble&lt;/em&gt; should not be confused with univaria&lt;em&gt;te&lt;/em&gt;/multivaria&lt;em&gt;te&lt;/em&gt;. The number of dependent variables characterizes the model as univariate or multivariate; univariate refers to a model with only one dependent variable, while multivariate refers to a model that simultaneously predicts more than one dependent variable. Usually, the intent is to differentiate models based on the number of independent variables. This distinction is made thanks to the terms univariable and multivariable. Multivariable refers to a model relating multiple predictor variables to a dependent variable, whereas univariable refers to a model relating one single independent variable to a dependent variable.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;data&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Data&lt;/h1&gt;
&lt;p&gt;For these illustrations, we use the “Heart Disease” dataset, available from the &lt;code&gt;{kmed}&lt;/code&gt; R package. This data frame consists of 14 variables, of which only 5 of them are kept for this post:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;code&gt;age&lt;/code&gt;: age in years&lt;/li&gt;
&lt;li&gt;&lt;code&gt;sex&lt;/code&gt;: sex (FALSE = female, TRUE = male)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;cp&lt;/code&gt;: chest pain type (1 = typical angina, 2 = atypical angina, 3 = non-anginal pain, 4 = asymptomatic)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;thalach&lt;/code&gt;: maximum heart rate achieved&lt;/li&gt;
&lt;li&gt;&lt;code&gt;class&lt;/code&gt;: diagnosis of heart disease (divided into 4 classes)&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# import and rename dataset
library(kmed)
dat &amp;lt;- heart

# select variables
library(dplyr)
dat &amp;lt;- dat |&amp;gt;
  select(
    age,
    sex,
    cp,
    thalach,
    class
  )

# print dataset&amp;#39;s structure
str(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## &amp;#39;data.frame&amp;#39;:	297 obs. of  5 variables:
##  $ age    : num  63 67 67 37 41 56 62 57 63 53 ...
##  $ sex    : logi  TRUE TRUE TRUE TRUE FALSE TRUE ...
##  $ cp     : Factor w/ 4 levels &amp;quot;1&amp;quot;,&amp;quot;2&amp;quot;,&amp;quot;3&amp;quot;,&amp;quot;4&amp;quot;: 1 4 4 3 2 2 4 4 4 4 ...
##  $ thalach: num  150 108 129 187 172 178 160 163 147 155 ...
##  $ class  : int  0 2 1 0 0 0 3 0 2 1 ...
##  - attr(*, &amp;quot;na.action&amp;quot;)= &amp;#39;omit&amp;#39; Named int [1:6] 88 167 193 267 288 303
##   ..- attr(*, &amp;quot;names&amp;quot;)= chr [1:6] &amp;quot;88&amp;quot; &amp;quot;167&amp;quot; &amp;quot;193&amp;quot; &amp;quot;267&amp;quot; ...&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the pipe operator &lt;code&gt;|&amp;gt;&lt;/code&gt; and the &lt;code&gt;{dplyr}&lt;/code&gt; package is used to select variables. See &lt;a href=&#34;https://statsandr.com/blog/introduction-to-data-manipulation-in-r-with-dplyr/&#34;&gt;more data manipulation techniques&lt;/a&gt; using this package if you are interested.&lt;/p&gt;
&lt;p&gt;For greater readability, we rename the variables &lt;code&gt;cp&lt;/code&gt;, &lt;code&gt;thalach&lt;/code&gt; and &lt;code&gt;class&lt;/code&gt; with more informative names:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# rename variables
dat &amp;lt;- dat |&amp;gt;
  rename(
    chest_pain = cp,
    max_heartrate = thalach,
    heart_disease = class
  )&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We transform the variables &lt;code&gt;sex&lt;/code&gt; and &lt;code&gt;chest_pain&lt;/code&gt; into &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#factor&#34;&gt;factor&lt;/a&gt; and set the labels accordingly:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# recode sex
dat$sex &amp;lt;- factor(dat$sex,
  levels = c(FALSE, TRUE),
  labels = c(&amp;quot;female&amp;quot;, &amp;quot;male&amp;quot;)
)

# recode chest_pain
dat$chest_pain &amp;lt;- factor(dat$chest_pain,
  levels = 1:4,
  labels = c(&amp;quot;typical angina&amp;quot;, &amp;quot;atypical angina&amp;quot;, &amp;quot;non-anginal pain&amp;quot;, &amp;quot;asymptomatic&amp;quot;)
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For a binary logistic regression in R, it is recommended that all the qualitative variables are transformed into factors.&lt;/p&gt;
&lt;p&gt;In our case, &lt;code&gt;heart_disease&lt;/code&gt; (our dependent variable) is currently encoded as &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#integer&#34;&gt;integer&lt;/a&gt; with values ranging from 0 to 4. Therefore, we first classify it into 2 classes by setting 0 for 0 values and 1 for non-0 values, using the &lt;code&gt;ifelse()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# recode heart_disease into 2 classes
dat$heart_disease &amp;lt;- ifelse(dat$heart_disease == 0,
  0,
  1
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We then transform it into a factor and set the labels accordingly using the &lt;code&gt;factor()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# set labels for heart_disease
dat$heart_disease &amp;lt;- factor(dat$heart_disease,
  levels = c(0, 1),
  labels = c(&amp;quot;no disease&amp;quot;, &amp;quot;disease&amp;quot;)
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Keep in mind the order of the levels for your dependent variable, as it will have an impact on the interpretations. In R, the first level given by &lt;code&gt;levels()&lt;/code&gt; is always taken as the reference level.&lt;/p&gt;
&lt;p&gt;In our case, the first level is the absence of the disease and the second level is the presence of the disease:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;levels(dat$heart_disease)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;no disease&amp;quot; &amp;quot;disease&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This means that when we will build the models, we will estimate the impact of the independent variable(s) on the &lt;strong&gt;presence&lt;/strong&gt; of the disease (and not the absence!).&lt;/p&gt;
&lt;p&gt;This is the reason that, for dependent variables of the type no/yes, false/true, absence/presence of a condition, etc. it is recommended to set the level no, false, absence of the condition, etc. as the reference level. It is indeed usually easier to interpret the impact of an independent variable on the presence of a condition/disease than the opposite.&lt;/p&gt;
&lt;p&gt;If you want to switch the reference level, this can be done with the &lt;code&gt;relevel()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;Here is a preview of the final data frame and some basic &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# print first 6 observations
head(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   age    sex       chest_pain max_heartrate heart_disease
## 1  63   male   typical angina           150    no disease
## 2  67   male     asymptomatic           108       disease
## 3  67   male     asymptomatic           129       disease
## 4  37   male non-anginal pain           187    no disease
## 5  41 female  atypical angina           172    no disease
## 6  56   male  atypical angina           178    no disease&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# basic descriptive statistics
summary(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       age            sex                 chest_pain  max_heartrate  
##  Min.   :29.00   female: 96   typical angina  : 23   Min.   : 71.0  
##  1st Qu.:48.00   male  :201   atypical angina : 49   1st Qu.:133.0  
##  Median :56.00                non-anginal pain: 83   Median :153.0  
##  Mean   :54.54                asymptomatic    :142   Mean   :149.6  
##  3rd Qu.:61.00                                       3rd Qu.:166.0  
##  Max.   :77.00                                       Max.   :202.0  
##     heart_disease
##  no disease:160  
##  disease   :137  
##                  
##                  
##                  
## &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The data frame is now ready to be analyzed further through univariable and multivariable binary logistic regressions.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;binary-logistic-regression-in-r&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Binary logistic regression in R&lt;/h1&gt;
&lt;div id=&#34;univariable-binary-logistic-regression&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Univariable binary logistic regression&lt;/h2&gt;
&lt;p&gt;As mentioned above, we start with a univariable binary logistic regression, that is, a binary logistic regression with only one independent variable.&lt;/p&gt;
&lt;p&gt;In R, a binary logistic regression can be done with the &lt;code&gt;glm()&lt;/code&gt; function and the &lt;code&gt;family = &#34;binomial&#34;&lt;/code&gt; argument. Similar to linear regression, the formula used inside the function must be written as &lt;code&gt;dependent variable ~ independent variable&lt;/code&gt; (in this order!).&lt;/p&gt;
&lt;p&gt;While the dependent variable must be categorical with two levels, the independent variable can be of any type. However, interpretations differ depending on whether the independent variable is qualitative or quantitative.&lt;/p&gt;
&lt;p&gt;For completeness, we illustrate this type of regression with both a quantitative and a qualitative independent variable, starting with a quantitative independent variable.&lt;/p&gt;
&lt;div id=&#34;quantitative-independent-variable&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Quantitative independent variable&lt;/h3&gt;
&lt;p&gt;Suppose we want to estimate the impact of a patient’s age on the presence of heart disease. In this case, &lt;code&gt;age&lt;/code&gt; is our independent variable and &lt;code&gt;heart_disease&lt;/code&gt; is our dependent variable:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# save model
m1 &amp;lt;- glm(heart_disease ~ age,
  data = dat,
  family = &amp;quot;binomial&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Results of the model is saved under the object &lt;code&gt;m1&lt;/code&gt;. Again, similar to linear regression, results can be accessed thanks to the &lt;code&gt;summary()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# print results
summary(m1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
## glm(formula = heart_disease ~ age, family = &amp;quot;binomial&amp;quot;, data = dat)
## 
## Coefficients:
##             Estimate Std. Error z value Pr(&amp;gt;|z|)    
## (Intercept) -3.05122    0.76862  -3.970  7.2e-05 ***
## age          0.05291    0.01382   3.829 0.000128 ***
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 409.95  on 296  degrees of freedom
## Residual deviance: 394.25  on 295  degrees of freedom
## AIC: 398.25
## 
## Number of Fisher Scoring iterations: 4&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The most important results in this output are displayed in the table after &lt;code&gt;Coefficients&lt;/code&gt;. The bottom part of the output summarizes the distribution of the deviance residuals. In a nutshell, deviance residuals measure how well the observations fit the model. The closer the residual to 0, the better the fit of the observation.&lt;/p&gt;
&lt;p&gt;Within the &lt;code&gt;Coefficients&lt;/code&gt; table, we focus on the first and last columns (the other two columns correspond to the standard error and the test statistic, which are both used to compute the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the column &lt;code&gt;Estimate&lt;/code&gt; corresponds to the coefficients &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_0\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_1\)&lt;/span&gt;, and&lt;/li&gt;
&lt;li&gt;the column &lt;code&gt;Pr(&amp;gt;|z|)&lt;/code&gt; corresponds to the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;R performs a &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis test&lt;/a&gt; for each coefficient, that is, &lt;span class=&#34;math inline&#34;&gt;\(H_0: \beta_j = 0\)&lt;/span&gt; versus &lt;span class=&#34;math inline&#34;&gt;\(H_1: \beta_j \neq 0\)&lt;/span&gt; for &lt;span class=&#34;math inline&#34;&gt;\(j = 0, 1\)&lt;/span&gt; via the Wald test, and print the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values in the last column. We can thus compare these &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values to the chosen significance level (usually &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;) to conclude whether or not each of the coefficient is significantly different from 0. The lower the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value, the more evidence that the coefficient is different from 0. This is similar to linear regression.&lt;/p&gt;
&lt;p&gt;Coefficients are slightly harder to interpret in logistic regression than in linear regression because the relationship between dependent and independent variables is not linear.&lt;/p&gt;
&lt;p&gt;Let’s first interpret the coefficient of age, &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_1\)&lt;/span&gt;, which is the most important coefficient of the two.&lt;/p&gt;
&lt;p&gt;First, since the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value of the test on the coefficient for age is &amp;lt; 0.05, we conclude that it is significantly different from 0, which means that age is significantly associated with the presence of heart disease (at the 5% significance level). Note that if the test was not significant (i.e., the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &lt;span class=&#34;math inline&#34;&gt;\(\ge \alpha\)&lt;/span&gt;), we would refrain from interpreting the coefficient since it means that, based on the data at hand, we are unable to conclude that age is associated with the presence of heart disease in the population.&lt;/p&gt;
&lt;p&gt;Second, remember that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;when &lt;span class=&#34;math inline&#34;&gt;\(\beta_1 = 0\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; are independent,&lt;/li&gt;
&lt;li&gt;when &lt;span class=&#34;math inline&#34;&gt;\(\beta_1 &amp;gt; 0\)&lt;/span&gt;, the probability that &lt;span class=&#34;math inline&#34;&gt;\(Y = 1\)&lt;/span&gt; &lt;em&gt;increases&lt;/em&gt; with &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt;, and&lt;/li&gt;
&lt;li&gt;when &lt;span class=&#34;math inline&#34;&gt;\(\beta_1 &amp;lt; 0\)&lt;/span&gt;, the probability that &lt;span class=&#34;math inline&#34;&gt;\(Y = 1\)&lt;/span&gt; &lt;em&gt;decreases&lt;/em&gt; with &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In our context, we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;when &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_1 = 0\)&lt;/span&gt;, the probability of developing a heart disease is &lt;em&gt;independent&lt;/em&gt; of the age,&lt;/li&gt;
&lt;li&gt;when &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_1 &amp;gt; 0\)&lt;/span&gt;, the probability of developing a heart disease &lt;em&gt;increases&lt;/em&gt; with age, and&lt;/li&gt;
&lt;li&gt;when &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_1 &amp;lt; 0\)&lt;/span&gt;, the probability of developing a heart disease &lt;em&gt;decreases&lt;/em&gt; with age.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here we have &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_1 =\)&lt;/span&gt; 0.053 &lt;span class=&#34;math inline&#34;&gt;\(&amp;gt; 0\)&lt;/span&gt;, so we already know that the older the patient, the more likely he or she is to develop a heart disease. This makes sense.&lt;/p&gt;
&lt;p&gt;Now that we know the direction of the relationship, we would like to &lt;strong&gt;quantify&lt;/strong&gt; this relationship. This is easily done thanks to odds ratios (OR). OR are found by taking the exponential of the coefficients. In R, the exponential is done thanks to the &lt;code&gt;exp()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;OR can be interpreted as follows: the OR is the multiplicative change in the odds in favor of &lt;span class=&#34;math inline&#34;&gt;\(Y = 1\)&lt;/span&gt; when &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; increases by 1 unit.&lt;/p&gt;
&lt;p&gt;Applied to our context, we compute the OR for the age by computing &lt;span class=&#34;math inline&#34;&gt;\(\exp(\hat{\beta}_1) =\)&lt;/span&gt; exp(0.053).&lt;/p&gt;
&lt;p&gt;Using R, this gives:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# OR for age
exp(coef(m1)[&amp;quot;age&amp;quot;])&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      age 
## 1.054331&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Based on this result, we can say that an extra year of age increases the odds (that is, the chance) of developing a heart disease by a factor of 1.054.&lt;/p&gt;
&lt;p&gt;Therefore, the odds of developing a heart disease increases by (1.054 - 1) &lt;span class=&#34;math inline&#34;&gt;\(\times\)&lt;/span&gt; 100 = 5.4% when a patient becomes one year older.&lt;/p&gt;
&lt;p&gt;To sum up:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;when the coefficient &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_1 = 0 \Rightarrow\)&lt;/span&gt; OR &lt;span class=&#34;math inline&#34;&gt;\(= \exp(\hat{\beta}_1) = 1 \Rightarrow P(Y = 1)\)&lt;/span&gt; is &lt;em&gt;independent&lt;/em&gt; of &lt;span class=&#34;math inline&#34;&gt;\(X \Rightarrow\)&lt;/span&gt; there is &lt;em&gt;no&lt;/em&gt; relationship between &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt;,&lt;/li&gt;
&lt;li&gt;when the coefficient &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_1 &amp;gt; 0 \Rightarrow\)&lt;/span&gt; OR &lt;span class=&#34;math inline&#34;&gt;\(= \exp(\hat{\beta}_1) &amp;gt; 1 \Rightarrow P(Y = 1)\)&lt;/span&gt; &lt;em&gt;increases&lt;/em&gt; with &lt;span class=&#34;math inline&#34;&gt;\(X \Rightarrow\)&lt;/span&gt; there is a &lt;em&gt;positive&lt;/em&gt; relationship between &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt;, and&lt;/li&gt;
&lt;li&gt;when the coefficient &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_1 &amp;lt; 0 \Rightarrow\)&lt;/span&gt; OR &lt;span class=&#34;math inline&#34;&gt;\(= \exp(\hat{\beta}_1) &amp;lt; 1 \Rightarrow P(Y = 1)\)&lt;/span&gt; &lt;em&gt;decreases&lt;/em&gt; with &lt;span class=&#34;math inline&#34;&gt;\(X \Rightarrow\)&lt;/span&gt; there is a &lt;em&gt;negative&lt;/em&gt; relationship between &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We now interpret the intercept &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_0\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;First, we look at the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value of the test on the intercept. This &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value being &amp;lt; 0.05, we conclude that the intercept is significantly different from 0 (at the 5% significance level).&lt;/p&gt;
&lt;p&gt;Second, similar to linear regression, in order to obtain an interpretation of the intercept, we need to find a situation in which the other coefficient, &lt;span class=&#34;math inline&#34;&gt;\(\beta_1\)&lt;/span&gt;, vanishes.&lt;/p&gt;
&lt;p&gt;In our case, it happens when a patient is 0 year old. We may or may not need to interpret results in a such a situation, and in many situations the interpretation does not make sense, so it is more a hypothetical interpretation. However, again for completeness we show how to interpret the intercept. Note that it is also possible to center the numeric variable so that the intercept has a more meaningful interpretation. This, however, goes beyond the scope of the post.&lt;/p&gt;
&lt;p&gt;For a patient aged 0 year, the odds of developing a heart disease is &lt;span class=&#34;math inline&#34;&gt;\(\exp(\hat{\beta}_0) =\)&lt;/span&gt; exp(-3.051) = 0.047. When interpreting an intercept, it often makes more sense to interpret it as the probability that &lt;span class=&#34;math inline&#34;&gt;\(Y = 1\)&lt;/span&gt;, which can be computed as follows:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\frac{\exp(\hat{\beta}_0)}{1 + \exp(\hat{\beta}_0)}.\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In our case, it corresponds to the probability that a patient of age 0 develops a heart disease, which is equal to:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# prob(heart disease) for age = 0
exp(coef(m1)[1]) / (1 + exp(coef(m1)[1]))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## (Intercept) 
##  0.04516478&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This means that, if we trust our model, a newborn is expected to develops a heart disease with a probability of 4.52%.&lt;/p&gt;
&lt;p&gt;For your information, a confidence interval can be computed for any of the OR using the &lt;code&gt;confint()&lt;/code&gt; function. For example, a 95% confidence interval for the OR for age:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# 95% CI for the OR for age
exp(confint(m1,
  parm = &amp;quot;age&amp;quot;
))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    2.5 %   97.5 % 
## 1.026699 1.083987&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Remember than when evaluating an OR, the null value is 1, not 0. An OR of 1 in this study would mean that there is no association between the age and the presence of heart disease. If the 95% confidence interval of the OR does not include 1, we conclude that there is a significant association between the age and the presence of heart disease. On the contrary, if it includes 1, we do not reject the hypothesis that there is no association between age and the presence of heart disease.&lt;/p&gt;
&lt;p&gt;In our case, the 95% CI does not include 1, so we conclude, at the 5% significance level, that there is a significant association between age and the presence of heart disease.&lt;/p&gt;
&lt;p&gt;You will notice that it is the same conclusion than with the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value. This is normal, it will always be the case:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;if the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &amp;lt; 0.05, 1 will not be included in the 95% CI, and&lt;/li&gt;
&lt;li&gt;if the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &lt;span class=&#34;math inline&#34;&gt;\(\ge\)&lt;/span&gt; 0.05, 1 will be included in the 95% CI.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This means that you can choose whether you draw your conclusion about the association between the two variables based on the 95% CI or the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value.&lt;/p&gt;
&lt;p&gt;Estimating the relationship between variables is the main reason for building models. Another goal is to predict the dependent variable based on newly observed values of the independent variable(s). This can be done with the &lt;code&gt;predict()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;Suppose we would like to predict the probability of developing a heart disease for a patient aged 30 years old:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# predict probability to develop heart disease
pred &amp;lt;- predict(m1,
  newdata = data.frame(age = c(30)),
  type = &amp;quot;response&amp;quot;
)

# print prediction
pred&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##         1 
## 0.1878525&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is predicted that a 30-year-old patient has a 18.79% chance of developing a heart disease.&lt;/p&gt;
&lt;p&gt;Note that if you would like to construct a confidence interval for this prediction, it can be done by adding the &lt;code&gt;se = TRUE&lt;/code&gt; argument in the &lt;code&gt;predict()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# predict probability to develop heart disease
pred &amp;lt;- predict(m1,
  newdata = data.frame(age = c(30)),
  type = &amp;quot;response&amp;quot;,
  se = TRUE
)

# print prediction
pred$fit&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##         1 
## 0.1878525&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# 95% confidence interval for the prediction
lower &amp;lt;- pred$fit - (qnorm(0.975) * pred$se.fit)
upper &amp;lt;- pred$fit + (qnorm(0.975) * pred$se.fit)
c(lower, upper)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##          1          1 
## 0.07873357 0.29697138&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you are a frequent reader of the blog, you are probably know that I like visualizations. The &lt;code&gt;plot_model()&lt;/code&gt; function available in the &lt;code&gt;{sjPlot}&lt;/code&gt; R package does a good job of visualizing results of the model:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load package
library(sjPlot)

# plot
plot_model(m1,
  type = &amp;quot;pred&amp;quot;,
  terms = &amp;quot;age&amp;quot;
) +
  labs(y = &amp;quot;Prob(heart disease)&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/index_files/figure-html/unnamed-chunk-19-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;For those of you who are familiar with the &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;&lt;code&gt;{ggplot2}&lt;/code&gt; package&lt;/a&gt;, you will have noticed that the function accepts layers from the &lt;code&gt;{ggplot2}&lt;/code&gt; package. Note also that this function works with other types of model (such as linear models).&lt;/p&gt;
&lt;p&gt;The above plot shows the probability of developing a heart disease in function of age, and confirms results found above:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;We see that the probability of developing a heart disease increases with age (which was expected given that the OR for the coefficient of age is &amp;gt; 1),&lt;/li&gt;
&lt;li&gt;and we also see that the probability of developing a heart disease for a 30-year-old patient is slightly below 20%.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;qualitative-independent-variable&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Qualitative independent variable&lt;/h3&gt;
&lt;p&gt;Suppose now that we are interested in estimating the relationship between the probability of developing a heart disease and the sex (which is a qualitative variable).&lt;/p&gt;
&lt;p&gt;Recall that when the independent variable was quantitative, &lt;span class=&#34;math inline&#34;&gt;\(\exp(\hat{\beta}_1)\)&lt;/span&gt; was the multiplicative change in the odds in favor of &lt;span class=&#34;math inline&#34;&gt;\(Y = 1\)&lt;/span&gt; as &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; increases by 1 unit.&lt;/p&gt;
&lt;p&gt;With &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; being the sex, the only unit increase possible is from 0 to 1 (or from 1 to 2 if sex is encoded as a factor), so we can write an interpretation in terms of female/male:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\exp(\hat{\beta}_1)\)&lt;/span&gt; is the multiplicative change of the odds in favor of &lt;span class=&#34;math inline&#34;&gt;\(Y = 1\)&lt;/span&gt; as a female becomes a male.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Again, keep in mind what is the order of the level for the variable sex. In our case, the level female comes before the level male:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# levels for sex
levels(dat$sex)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;female&amp;quot; &amp;quot;male&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So it is indeed the multiplicative change of the odds in favor of &lt;span class=&#34;math inline&#34;&gt;\(Y = 1\)&lt;/span&gt; &lt;strong&gt;as a female becomes a male&lt;/strong&gt;. If the level male came before the level female in our dataset, it would have been the opposite.&lt;/p&gt;
&lt;p&gt;You will concede that it is rather strange to interpret odds as a female becomes a male, or vice versa. Therefore, it is better to say:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\exp(\hat{\beta}_1)\)&lt;/span&gt; is the multiplicative change of the odds in favor of &lt;span class=&#34;math inline&#34;&gt;\(Y = 1\)&lt;/span&gt; for &lt;strong&gt;males versus females&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In our case, we obtain the following results:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# save model
m2 &amp;lt;- glm(heart_disease ~ sex,
  data = dat,
  family = &amp;quot;binomial&amp;quot;
)

# print results
summary(m2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
## glm(formula = heart_disease ~ sex, family = &amp;quot;binomial&amp;quot;, data = dat)
## 
## Coefficients:
##             Estimate Std. Error z value Pr(&amp;gt;|z|)    
## (Intercept)  -1.0438     0.2326  -4.488 7.18e-06 ***
## sexmale       1.2737     0.2725   4.674 2.95e-06 ***
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 409.95  on 296  degrees of freedom
## Residual deviance: 386.12  on 295  degrees of freedom
## AIC: 390.12
## 
## Number of Fisher Scoring iterations: 4&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# OR for sex
exp(coef(m2)[&amp;quot;sexmale&amp;quot;])&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  sexmale 
## 3.573933&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;which can be interpreted as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value of the test on the coefficient for sex is &amp;lt; 0.05, so we conclude that the sex is significantly associated with the presence of heart disease (at the 5% significance level).&lt;/li&gt;
&lt;li&gt;Moreover, when looking at the coefficient for sex, &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_1 =\)&lt;/span&gt; 1.274, we can say that:
&lt;ul&gt;
&lt;li&gt;For males, the odds of developing a heart disease is multiplied by a factor of exp(1.274) = 3.574 compared to females.&lt;/li&gt;
&lt;li&gt;In other words, the odds of developing a heart disease for males are 3.574 times the odds for females.&lt;/li&gt;
&lt;li&gt;This means that, the odds of developing a heart disease are (3.574 - 1) &lt;span class=&#34;math inline&#34;&gt;\(\times\)&lt;/span&gt; 100 = 257.4% higher for males than for females.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These results again make sense, as it known that men are more likely to have a heart disease than women.&lt;/p&gt;
&lt;p&gt;The interpretation of the intercept &lt;span class=&#34;math inline&#34;&gt;\(\hat{\beta}_0 =\)&lt;/span&gt; -1.044 is similar than in the previous section in the sense that it gives the probability of developing a heart disease when the other coefficient, &lt;span class=&#34;math inline&#34;&gt;\(\beta_1\)&lt;/span&gt;, is equal to 0.&lt;/p&gt;
&lt;p&gt;In our case, &lt;span class=&#34;math inline&#34;&gt;\(\beta_1 = 0\)&lt;/span&gt; simply means that the patient is a female. Therefore, the probability of developing a heart disease for a woman is:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# prob(disease) for sex = female
exp(coef(m2)[1]) / (1 + exp(coef(m2)[1]))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## (Intercept) 
##   0.2604167&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The avid reader will notice that a univariable binary logistic regression with a qualitative independent variable will lead to the same conclusion than a &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;Chi-square test of independence&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;chisq.test(table(dat$heart_disease, dat$sex))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Pearson&amp;#39;s Chi-squared test with Yates&amp;#39; continuity correction
## 
## data:  table(dat$heart_disease, dat$sex)
## X-squared = 21.852, df = 1, p-value = 2.946e-06&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Based on this test, we reject the null hypothesis of independence between the two variables and we thus conclude that there is a significant association between the sex and the presence of heart disease (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &amp;lt; 0.001).&lt;/p&gt;
&lt;p&gt;The advantage of a univariable binary logistic regression over a Chi-square test of independence is that it not only tests whether or not there is a significant association between the two variables, but it also &lt;strong&gt;estimates the direction and strength of this relationship&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;As for a univariable logistic regression with a quantitative independent variable, predictions can also be made with the &lt;code&gt;predict()&lt;/code&gt; function. Suppose we would like to predict the probability of developing a heart disease for a male:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# predict probability to develop heart disease
pred &amp;lt;- predict(m2,
  newdata = data.frame(sex = c(&amp;quot;male&amp;quot;)),
  type = &amp;quot;response&amp;quot;
)

# print prediction
pred&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##         1 
## 0.5572139&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Based on this model, it is predicted that a male patient has 55.72% chance of developing a heart disease.&lt;/p&gt;
&lt;p&gt;We can also visualize these results thanks to the &lt;code&gt;plot_model()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# plot
plot_model(m2,
  type = &amp;quot;pred&amp;quot;,
  terms = &amp;quot;sex&amp;quot;
) +
  labs(y = &amp;quot;Prob(heart disease)&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/index_files/figure-html/unnamed-chunk-25-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The points correspond to the predicted probabilities, and the bars correspond to their confidence intervals.&lt;/p&gt;
&lt;p&gt;The plot of the results in terms of probabilities confirms what was found above, that is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;women are less likely to develop a heart disease than men,&lt;/li&gt;
&lt;li&gt;the probability that a woman develops a heart disease is expected to be slightly above 25%, and&lt;/li&gt;
&lt;li&gt;the probability that a man develops a heart disease is expected to be around 55%.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;multivariable-binary-logistic-regression&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Multivariable binary logistic regression&lt;/h2&gt;
&lt;p&gt;The interpretation of the coefficients in multivariable logistic regression is similar to the interpretation in univariable regression, except that this time it estimates the multiplicative change in the odds in favor of &lt;span class=&#34;math inline&#34;&gt;\(Y = 1\)&lt;/span&gt; when &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; increases by 1 unit, &lt;strong&gt;while the other independent variables remain unchanged&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;This is similar to multiple linear regression, where a coefficient gives the expected change of &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; for an increase of 1 unit of &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt;, while keeping all other variables constant.&lt;/p&gt;
&lt;p&gt;The main advantages of using a multivariable logistic regression compared to a univariable logistic regression are to:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;consider the simultaneous (rather than isolated) effect of independent variables,&lt;/li&gt;
&lt;li&gt;take into account potential confounding and/or interaction effects, and&lt;/li&gt;
&lt;li&gt;improve predictions.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For this illustration, suppose we would like to estimate the relationship between heart disease and all variables present in the data frame, that is, age, sex, chest pain type and maximum heart rate achieved:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# save model
m3 &amp;lt;- glm(heart_disease ~ .,
  data = dat,
  family = &amp;quot;binomial&amp;quot;
)

# print results
summary(m3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
## glm(formula = heart_disease ~ ., family = &amp;quot;binomial&amp;quot;, data = dat)
## 
## Coefficients:
##                             Estimate Std. Error z value Pr(&amp;gt;|z|)    
## (Intercept)                -0.060150   1.962091  -0.031 0.975544    
## age                         0.042814   0.019009   2.252 0.024302 *  
## sexmale                     1.686330   0.349352   4.827 1.39e-06 ***
## chest_painatypical angina  -0.120481   0.641396  -0.188 0.851000    
## chest_painnon-anginal pain -0.124331   0.571093  -0.218 0.827658    
## chest_painasymptomatic      1.963723   0.548877   3.578 0.000347 ***
## max_heartrate              -0.030326   0.007975  -3.802 0.000143 ***
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 409.95  on 296  degrees of freedom
## Residual deviance: 275.26  on 290  degrees of freedom
## AIC: 289.26
## 
## Number of Fisher Scoring iterations: 5&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the formula &lt;code&gt;heart_disease ~ .&lt;/code&gt; is a shortcut to include all variables present in the data frame in the model as independent variables, except &lt;code&gt;heart_disease&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Based on the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values displayed in the last column of the coefficients table, we conclude that, at the 5% significance level, age, sex and maximum heart rate achieved are all significantly associated with heart disease (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values &amp;lt; 0.05).&lt;/p&gt;
&lt;p&gt;For the variables &lt;code&gt;age&lt;/code&gt;, &lt;code&gt;sex&lt;/code&gt; and &lt;code&gt;max_heartrate&lt;/code&gt;, there is only one &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value (the result of the test on the nullity of the coefficient).&lt;/p&gt;
&lt;p&gt;For the variable &lt;code&gt;chest_pain&lt;/code&gt;, 3 &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values are displayed. This is normal: similar to linear regression when a categorical variable with more than two levels is included in the model, one test is performed for each comparison between the reference level and the other levels.&lt;/p&gt;
&lt;p&gt;In our case, the reference level for the variable &lt;code&gt;chest_pain&lt;/code&gt; is &lt;code&gt;typical angina&lt;/code&gt; as it comes first:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;levels(dat$chest_pain)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;typical angina&amp;quot;   &amp;quot;atypical angina&amp;quot;  &amp;quot;non-anginal pain&amp;quot; &amp;quot;asymptomatic&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Therefore, a test is performed for the comparison between:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;code&gt;typical angina&lt;/code&gt; and &lt;code&gt;atypical angina&lt;/code&gt;,&lt;/li&gt;
&lt;li&gt;&lt;code&gt;typical angina&lt;/code&gt; and &lt;code&gt;non-anginal pain&lt;/code&gt;, and&lt;/li&gt;
&lt;li&gt;&lt;code&gt;typical angina&lt;/code&gt; and &lt;code&gt;asymptomatic&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;But here we are not interested in comparing levels of the variable chest pain, we would like to test the overall effect of chest pain on heart disease. For this, we are going to compare two models via a likelihood ratio test (LRT):&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;a model which includes all the variables of interest &lt;strong&gt;and&lt;/strong&gt; the variable &lt;code&gt;chest_pain&lt;/code&gt;, and&lt;/li&gt;
&lt;li&gt;the exact same model but which &lt;strong&gt;excludes&lt;/strong&gt; the variable &lt;code&gt;chest_pain&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The first one is referred as the full or complete model, whereas the second one is referred as the reduced model.&lt;/p&gt;
&lt;p&gt;We compare these two models with the &lt;code&gt;anova()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# save reduced model
m3_reduced &amp;lt;- glm(heart_disease ~ age + sex + max_heartrate,
  data = dat,
  family = &amp;quot;binomial&amp;quot;
)

# compare reduced with full model
anova(m3_reduced, m3,
  test = &amp;quot;LRT&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Analysis of Deviance Table
## 
## Model 1: heart_disease ~ age + sex + max_heartrate
## Model 2: heart_disease ~ age + sex + chest_pain + max_heartrate
##   Resid. Df Resid. Dev Df Deviance  Pr(&amp;gt;Chi)    
## 1       293     325.12                          
## 2       290     275.26  3    49.86 8.558e-11 ***
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice that the reduced model must come before the complete model in the &lt;code&gt;anova()&lt;/code&gt; function. The null hypothesis of this test is that the two models are equivalent.&lt;/p&gt;
&lt;p&gt;At the 5% significance level (see the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value at the right of the R output), we reject the null hypothesis and we conclude that the complete model is significantly better than the reduced model at explaining the presence of heart disease. This means that chest pain is significantly associated with heart disease (which was expected since the comparison between &lt;code&gt;typical angina&lt;/code&gt; and &lt;code&gt;asymptomatic&lt;/code&gt; was found to be significant).&lt;/p&gt;
&lt;p&gt;A comparison of two models via the LRT will be shown again later, when discussing about interactions.&lt;/p&gt;
&lt;p&gt;Now that we have shown that all four independent variables were significantly associated with the presence of heart disease, we can interpret the coefficients in order to know the direction of the relationships and most importantly, quantify the strength of these relationships.&lt;/p&gt;
&lt;p&gt;Like univariable binary logistic regression, it is easier to interpret these relationships through OR. But this time, we also print the 95% CI of the OR in addition to the OR (rounded to 3 decimals) so that we can easily see which ones are significantly different from 1:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# OR and 95% CI
round(exp(cbind(OR = coef(m3), confint(m3))), 3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##                               OR 2.5 % 97.5 %
## (Intercept)                0.942 0.020 44.353
## age                        1.044 1.006  1.084
## sexmale                    5.400 2.776 10.971
## chest_painatypical angina  0.886 0.252  3.191
## chest_painnon-anginal pain 0.883 0.293  2.814
## chest_painasymptomatic     7.126 2.509 22.030
## max_heartrate              0.970 0.955  0.985&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From the OR and their 95% CI computed above, we conclude that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Age: the odds of having a heart disease are multiplied by a factor of 1.04 for each one-unit increase in age, all else being equal.&lt;/li&gt;
&lt;li&gt;Sex: the odds of developing a heart disease for males are 5.4 times the odds for females, all else being equal.&lt;/li&gt;
&lt;li&gt;Chest pain: the odds of developing a heart disease for people suffering from chest pain of the type “asymptomatic” are 7.13 times the odds for people suffering from chest pain of the type “typical angina”, all else being equal. We refrain from interpreting the other comparisons as they are not significant at the 5% significance level (1 is included in their 95% CI).&lt;/li&gt;
&lt;li&gt;Maximum heart rate achieved: the odds of having a heart disease are multiplied by a factor of 0.97 for each one-unit increase in maximum heart rate achieved, all else being equal.&lt;/li&gt;
&lt;li&gt;Intercept: we also refrain from interpreting the intercept as it is not significantly different from 0 at the 5% significance level (1 is included in the 95% CI).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If you are interested in printing only the OR for which the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value of the coefficient is &amp;lt; 0.05, here is the code:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;exp(coef(m3))[coef(summary(m3))[, &amp;quot;Pr(&amp;gt;|z|)&amp;quot;] &amp;lt; 0.05]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##                    age                sexmale chest_painasymptomatic 
##              1.0437437              5.3996293              7.1258054 
##          max_heartrate 
##              0.9701289&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Remember that we can always write the interpretations in terms of the percentage increase/decrease in odds with the formula &lt;span class=&#34;math inline&#34;&gt;\((OR - 1) \times 100\)&lt;/span&gt;, where OR corresponds to the odds ratio.&lt;/p&gt;
&lt;p&gt;For instance, for the maximum heart rate achieved, the OR = 0.97, so the interpretation becomes: the odds of developing a heart disease increases by (0.97 &lt;span class=&#34;math inline&#34;&gt;\(- 1) \times 100 =\)&lt;/span&gt; -3% for each one-unit increase in maximum heart rate achieved, which is equivalent to say that the odds of developing a heart disease &lt;em&gt;decreases&lt;/em&gt; by 3% for each one-unit increase in maximum heart rate achieved.&lt;/p&gt;
&lt;p&gt;For illustrative purposes, suppose now that we would like to predict the probability that a new patient develops a heart disease. Suppose that this patient is a 32-year-old woman, suffering from chest pain of the type non-anginal and she achieved a maximum heart rate of 150. The probability that she develops a heart disease is:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# create data frame of new patient
new_patient &amp;lt;- data.frame(
  age = 32,
  sex = &amp;quot;female&amp;quot;,
  chest_pain = &amp;quot;non-anginal pain&amp;quot;,
  max_heartrate = 150
)

# predict probability to develop heart disease
pred &amp;lt;- predict(m3,
  newdata = new_patient,
  type = &amp;quot;response&amp;quot;
)

# print prediction
pred&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##          1 
## 0.03345948&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If we trust our model, the probability that this new patient will develop a heart disease is predicted to be 3.35%.&lt;/p&gt;
&lt;p&gt;We can also visualize the results thanks to the &lt;code&gt;plot_model()&lt;/code&gt; function, three effects at the same time:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;effect of age, sex and chest pain type on the predicted probability of developing a heart disease, and&lt;/li&gt;
&lt;li&gt;effect of maximum heart rate achieved, sex and chest pain type on the predicted probability of developing a heart disease.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# 1. age, sex and chest pain on prob of disease
plot_model(m3,
  type = &amp;quot;pred&amp;quot;,
  terms = c(&amp;quot;age&amp;quot;, &amp;quot;chest_pain&amp;quot;, &amp;quot;sex&amp;quot;),
  ci.lvl = NA # remove confidence bands
) +
  labs(y = &amp;quot;Prob(heart disease)&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/index_files/figure-html/unnamed-chunk-32-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# 2. max heart rate, chest pain and sex on prob of disease
plot_model(m3,
  type = &amp;quot;pred&amp;quot;,
  terms = c(&amp;quot;max_heartrate&amp;quot;, &amp;quot;chest_pain&amp;quot;, &amp;quot;sex&amp;quot;),
  ci.lvl = NA # remove confidence bands
) +
  labs(y = &amp;quot;Prob(heart disease)&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/index_files/figure-html/unnamed-chunk-32-2.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;For more clarity in the plots, confidence bands are removed thanks to &lt;code&gt;ci.lvl = NA&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;These plots confirm results obtained above, that is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;there is a &lt;em&gt;positive&lt;/em&gt; relationship between age and the presence of heart disease,&lt;/li&gt;
&lt;li&gt;there is a &lt;em&gt;negative&lt;/em&gt; relationship between maximum heart rate achieved and the presence of heart disease,&lt;/li&gt;
&lt;li&gt;the odds of developing a heart disease is higher for patients suffering from chest pain of the type asymptomatic and similar for the 3 other types of chest pain, and&lt;/li&gt;
&lt;li&gt;the odds of developing a heart disease is higher for males than for females.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;interaction&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Interaction&lt;/h2&gt;
&lt;p&gt;In the previous sections, potential interaction effects were omitted.&lt;/p&gt;
&lt;p&gt;An interaction occurs when the relationship between an independent variable and the outcome variable depends on the value or the level taken by another independent variable. On the contrary, if the relationship between an independent variable and the dependent variable remains unchanged no matter the value taken by another independent variable, we cannot conclude that there is an interaction effect.&lt;/p&gt;
&lt;p&gt;In our case, there would be an interaction if for example the relationship between age and heart disease depends on the sex. There would be an interaction, for instance, if the relationship between age and heart disease was positive for females, and negative for males, or vice versa. Or if the relationship between age and heart disease was much stronger or much weaker for females than for males.&lt;/p&gt;
&lt;p&gt;Let’s see if there is an interaction between age and sex, and more importantly, whether or not this interaction is significant. For this, we need to build two models:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;one model containing only the main effects, so without the interaction, and&lt;/li&gt;
&lt;li&gt;one model containing the main effects &lt;strong&gt;and&lt;/strong&gt; the interaction.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# save model without interaction
m4 &amp;lt;- glm(heart_disease ~ age + sex,
  data = dat,
  family = &amp;quot;binomial&amp;quot;
)

# save model with interaction
m4_inter &amp;lt;- glm(heart_disease ~ age * sex,
  data = dat,
  family = &amp;quot;binomial&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We first assess the interaction visually via the &lt;code&gt;plot_model()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# plot
plot_model(m4_inter,
  type = &amp;quot;pred&amp;quot;,
  terms = c(&amp;quot;age&amp;quot;, &amp;quot;sex&amp;quot;),
  ci.lvl = NA # remove confidence bands
) +
  labs(y = &amp;quot;Prob(heart disease)&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/index_files/figure-html/unnamed-chunk-34-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Since the two curves of the predicted probabilities are relatively similar and follow the same pattern, the relationship between age and the presence of heart disease does not seem to depend on the sex, indicating that there may indeed be no interaction. However, we would like to test it more formally via a statistical test.&lt;/p&gt;
&lt;p&gt;For this, we can compare the two models (the one without compared to the one with interaction) with a likelihood ratio test (LRT), using the &lt;code&gt;anova()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;anova(m4, m4_inter,
  test = &amp;quot;LRT&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Analysis of Deviance Table
## 
## Model 1: heart_disease ~ age + sex
## Model 2: heart_disease ~ age * sex
##   Resid. Df Resid. Dev Df Deviance Pr(&amp;gt;Chi)
## 1       294     364.43                     
## 2       293     364.23  1  0.20741   0.6488&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Remember that it is always the reduced model as the first argument in the &lt;code&gt;anova()&lt;/code&gt; function, and then the more complex model as the second argument.&lt;/p&gt;
&lt;p&gt;The test confirms what we supposed based on the plot: at the 5% significance level, we do not reject the null hypothesis that the two models are equivalent. Since the only difference between the two models is that an interaction term is added in the complete model, we do not reject the hypothesis that there is no interaction between the age and the sex (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.649).&lt;/p&gt;
&lt;p&gt;This conclusion could have also been obtained more simply with the &lt;code&gt;drop1()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;drop1(m4_inter,
  test = &amp;quot;LRT&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Single term deletions
## 
## Model:
## heart_disease ~ age * sex
##         Df Deviance    AIC     LRT Pr(&amp;gt;Chi)
## &amp;lt;none&amp;gt;       364.23 372.23                 
## age:sex  1   364.43 370.43 0.20741   0.6488&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, this gives the same &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value of 0.649.&lt;/p&gt;
&lt;p&gt;In practice, a non-significant interaction is removed from the model before interpreting its results. In our case, only the main effects of age and sex would remain in the model.&lt;/p&gt;
&lt;p&gt;This leads us to model selection, or which variables should be included in our final model. This is discussed in the next section.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;model-selection&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Model selection&lt;/h2&gt;
&lt;p&gt;In practice, we often have several models, corresponding to the different combinations of independent variables and their interactions. Finding the best model is not easy.&lt;/p&gt;
&lt;p&gt;In general, the best practice is to obtain a final model that is as parsimonious as possible, that is, with as few parameters as possible. A parsimonious model is easier to interpret and generalize, and also more powerful from a statistical point of view. On the other hand, it should not be too simple so that it still captures the variations or patterns in the data. In general, while more variables are often better than one, too many is often worse than a few.&lt;/p&gt;
&lt;p&gt;The two most common approaches to obtain a final model are the following:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Adjust the model by removing the main effects and their interactions which are not significant with respect to their &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values, obtained by testing the nullity of the corresponding coefficients using a statistical test such as the likelihood ratio test or the Wald test. If there are several main effects or interactions which are not significant, interactions must be removed before removing any main effect. Moreover, it is recommended to remove interactions and independent variables one by one (starting with the one with the highest &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value), as removing a variable or an interaction may make another variable or interaction that was initially non-significant significant.&lt;/li&gt;
&lt;li&gt;Adjust the model by using AIC (Akaike Information Criterion) or BIC (Bayesian Information Criterion). These procedures allow to select the best model (according to AIC or BIC) by finding an equilibrium between simplicity and complexity. These selection processes usually lead to a final model with as few parameters as possible, but which captures as much information in the data as possible. Note that only models with the same dependent variable can be compared using AIC or BIC. Models with different dependent variables cannot be compared using these criteria.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The first method requires that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the underlying assumptions are valid,&lt;/li&gt;
&lt;li&gt;the sample size is sufficiently large, and&lt;/li&gt;
&lt;li&gt;the models are nested (i.e., the complete model includes at least all the variables included in the reduced model).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Moreover, the second method can be used with widely used criteria when selecting variables, and more importantly, in a completely autonomous way in R.&lt;/p&gt;
&lt;p&gt;For this reason, the second method is recommended and more often used in practice.&lt;/p&gt;
&lt;p&gt;This second method, referred as the stepwise selection, is divided into 3 types:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;backward selection: we start from the most complete model (containing all independent variables and usually also their interactions), and the interactions/main effects are deleted at each step until the model cannot be improved,&lt;/li&gt;
&lt;li&gt;forward selection: we start from the most basic model containing only the intercept, and the independent variables/interactions are added at each step until the model cannot be improved, or&lt;/li&gt;
&lt;li&gt;mixed selection: we apply both the backward &lt;strong&gt;and&lt;/strong&gt; forward selection to determine the best model according to the desired criterion.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;We show how to select the best model according to AIC using the mixed stepwise selection, illustrated with all variables present in the data frame as independent variables and all possible second order interactions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# save initial model
m5 &amp;lt;- glm(heart_disease ~ (age + sex + chest_pain + max_heartrate)^2,
  data = dat,
  family = &amp;quot;binomial&amp;quot;
)

# select best model according to AIC using mixed selection
m5_final &amp;lt;- step(m5,
  direction = &amp;quot;both&amp;quot;, # both = mixed selection
  trace = FALSE # do not display intermediate steps
)

# display results of final model
summary(m5_final)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
## glm(formula = heart_disease ~ age + sex + chest_pain + max_heartrate + 
##     age:max_heartrate, family = &amp;quot;binomial&amp;quot;, data = dat)
## 
## Coefficients:
##                              Estimate Std. Error z value Pr(&amp;gt;|z|)    
## (Intercept)                19.4386591  8.1904201   2.373 0.017628 *  
## age                        -0.3050017  0.1414986  -2.156 0.031122 *  
## sexmale                     1.7055353  0.3507149   4.863 1.16e-06 ***
## chest_painatypical angina  -0.0086463  0.6547573  -0.013 0.989464    
## chest_painnon-anginal pain -0.0590333  0.5844000  -0.101 0.919538    
## chest_painasymptomatic      1.9724490  0.5649516   3.491 0.000481 ***
## max_heartrate              -0.1605658  0.0540933  -2.968 0.002994 ** 
## age:max_heartrate           0.0023314  0.0009433   2.471 0.013457 *  
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 409.95  on 296  degrees of freedom
## Residual deviance: 268.60  on 289  degrees of freedom
## AIC: 284.6
## 
## Number of Fisher Scoring iterations: 5&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;According to the AIC (which is the default criterion when using the &lt;code&gt;step()&lt;/code&gt; function), the best model is the one including:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;age&lt;/code&gt;,&lt;/li&gt;
&lt;li&gt;&lt;code&gt;sex&lt;/code&gt;,&lt;/li&gt;
&lt;li&gt;&lt;code&gt;chest_pain&lt;/code&gt;,&lt;/li&gt;
&lt;li&gt;&lt;code&gt;max_heartrate&lt;/code&gt;, and&lt;/li&gt;
&lt;li&gt;the interaction between &lt;code&gt;age&lt;/code&gt; and &lt;code&gt;max_heartrate&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For your information, you can also easily compare models manually using AIC or the pseudo-&lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; with the &lt;code&gt;tab_model()&lt;/code&gt; function, also available in the &lt;code&gt;{sjPlot}&lt;/code&gt; R package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;tab_model(m3, m4, m5_final,
  show.ci = FALSE, # remove CI
  show.aic = TRUE, # display AIC
  p.style = &amp;quot;numeric_stars&amp;quot; # display p-values and stars
)&lt;/code&gt;&lt;/pre&gt;
&lt;table style=&#34;border-collapse:collapse; border:none;&#34;&gt;
&lt;tr&gt;
&lt;th style=&#34;border-top: double; text-align:center; font-style:normal; font-weight:bold; padding:0.2cm;  text-align:left; &#34;&gt;
 
&lt;/th&gt;
&lt;th colspan=&#34;2&#34; style=&#34;border-top: double; text-align:center; font-style:normal; font-weight:bold; padding:0.2cm; &#34;&gt;
heart disease
&lt;/th&gt;
&lt;th colspan=&#34;2&#34; style=&#34;border-top: double; text-align:center; font-style:normal; font-weight:bold; padding:0.2cm; &#34;&gt;
heart disease
&lt;/th&gt;
&lt;th colspan=&#34;2&#34; style=&#34;border-top: double; text-align:center; font-style:normal; font-weight:bold; padding:0.2cm; &#34;&gt;
heart disease
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&#34; text-align:center; border-bottom:1px solid; font-style:italic; font-weight:normal;  text-align:left; &#34;&gt;
Predictors
&lt;/td&gt;
&lt;td style=&#34; text-align:center; border-bottom:1px solid; font-style:italic; font-weight:normal;  &#34;&gt;
Odds Ratios
&lt;/td&gt;
&lt;td style=&#34; text-align:center; border-bottom:1px solid; font-style:italic; font-weight:normal;  &#34;&gt;
p
&lt;/td&gt;
&lt;td style=&#34; text-align:center; border-bottom:1px solid; font-style:italic; font-weight:normal;  &#34;&gt;
Odds Ratios
&lt;/td&gt;
&lt;td style=&#34; text-align:center; border-bottom:1px solid; font-style:italic; font-weight:normal;  &#34;&gt;
p
&lt;/td&gt;
&lt;td style=&#34; text-align:center; border-bottom:1px solid; font-style:italic; font-weight:normal;  &#34;&gt;
Odds Ratios
&lt;/td&gt;
&lt;td style=&#34; text-align:center; border-bottom:1px solid; font-style:italic; font-weight:normal;  col7&#34;&gt;
p
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:left; &#34;&gt;
(Intercept)
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
0.94 &lt;sup&gt;&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
0.976
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
0.01 &lt;sup&gt;***&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;strong&gt;&amp;lt;0.001&lt;/strong&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
276759408.51 &lt;sup&gt;*&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  col7&#34;&gt;
&lt;strong&gt;0.018&lt;/strong&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:left; &#34;&gt;
age
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
1.04 &lt;sup&gt;*&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;strong&gt;0.024&lt;/strong&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
1.07 &lt;sup&gt;***&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;strong&gt;&amp;lt;0.001&lt;/strong&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
0.74 &lt;sup&gt;*&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  col7&#34;&gt;
&lt;strong&gt;0.031&lt;/strong&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:left; &#34;&gt;
sex [male]
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
5.40 &lt;sup&gt;***&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;strong&gt;&amp;lt;0.001&lt;/strong&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
4.47 &lt;sup&gt;***&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;strong&gt;&amp;lt;0.001&lt;/strong&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
5.50 &lt;sup&gt;***&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  col7&#34;&gt;
&lt;strong&gt;&amp;lt;0.001&lt;/strong&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:left; &#34;&gt;
chest pain [atypical&lt;br&gt;angina]
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
0.89 &lt;sup&gt;&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
0.851
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
0.99 &lt;sup&gt;&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  col7&#34;&gt;
0.989
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:left; &#34;&gt;
chest pain [non-anginal&lt;br&gt;pain]
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
0.88 &lt;sup&gt;&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
0.828
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
0.94 &lt;sup&gt;&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  col7&#34;&gt;
0.920
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:left; &#34;&gt;
chest pain [asymptomatic]
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
7.13 &lt;sup&gt;***&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;strong&gt;&amp;lt;0.001&lt;/strong&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
7.19 &lt;sup&gt;***&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  col7&#34;&gt;
&lt;strong&gt;&amp;lt;0.001&lt;/strong&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:left; &#34;&gt;
max heartrate
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
0.97 &lt;sup&gt;***&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;strong&gt;&amp;lt;0.001&lt;/strong&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
0.85 &lt;sup&gt;**&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  col7&#34;&gt;
&lt;strong&gt;0.003&lt;/strong&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:left; &#34;&gt;
age × max heartrate
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  &#34;&gt;
1.00 &lt;sup&gt;*&lt;/sup&gt;
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:center;  col7&#34;&gt;
&lt;strong&gt;0.013&lt;/strong&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:left; padding-top:0.1cm; padding-bottom:0.1cm; border-top:1px solid;&#34;&gt;
Observations
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; padding-top:0.1cm; padding-bottom:0.1cm; text-align:left; border-top:1px solid;&#34; colspan=&#34;2&#34;&gt;
297
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; padding-top:0.1cm; padding-bottom:0.1cm; text-align:left; border-top:1px solid;&#34; colspan=&#34;2&#34;&gt;
297
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; padding-top:0.1cm; padding-bottom:0.1cm; text-align:left; border-top:1px solid;&#34; colspan=&#34;2&#34;&gt;
297
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:left; padding-top:0.1cm; padding-bottom:0.1cm;&#34;&gt;
R&lt;sup&gt;2&lt;/sup&gt; Tjur
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; padding-top:0.1cm; padding-bottom:0.1cm; text-align:left;&#34; colspan=&#34;2&#34;&gt;
0.393
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; padding-top:0.1cm; padding-bottom:0.1cm; text-align:left;&#34; colspan=&#34;2&#34;&gt;
0.142
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; padding-top:0.1cm; padding-bottom:0.1cm; text-align:left;&#34; colspan=&#34;2&#34;&gt;
0.409
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; text-align:left; padding-top:0.1cm; padding-bottom:0.1cm;&#34;&gt;
AIC
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; padding-top:0.1cm; padding-bottom:0.1cm; text-align:left;&#34; colspan=&#34;2&#34;&gt;
289.263
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; padding-top:0.1cm; padding-bottom:0.1cm; text-align:left;&#34; colspan=&#34;2&#34;&gt;
370.435
&lt;/td&gt;
&lt;td style=&#34; padding:0.2cm; text-align:left; vertical-align:top; padding-top:0.1cm; padding-bottom:0.1cm; text-align:left;&#34; colspan=&#34;2&#34;&gt;
284.599
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td colspan=&#34;7&#34; style=&#34;font-style:italic; border-top:double black; text-align:right;&#34;&gt;
* p&amp;lt;0.05   ** p&amp;lt;0.01   *** p&amp;lt;0.001
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Pseudo-&lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; is a generalization of the coefficient of determination &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; often used in linear regression to judge the quality of a model. Like the &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; in linear regression, the pseudo-&lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; varies from 0 to 1, and can be interpreted as the percentage of the null deviance explained by the independent variable(s). The higher the pseudo-&lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; and the lower the AIC, the better the model.&lt;/p&gt;
&lt;p&gt;Note that there are several pseudo-&lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt;, such as:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Likelihood ratio &lt;span class=&#34;math inline&#34;&gt;\(R^2_{L}\)&lt;/span&gt;,&lt;/li&gt;
&lt;li&gt;Cox and Snell &lt;span class=&#34;math inline&#34;&gt;\(R^2_{CS}\)&lt;/span&gt;,&lt;/li&gt;
&lt;li&gt;Nagelkerke &lt;span class=&#34;math inline&#34;&gt;\(R^2_{N}\)&lt;/span&gt;,&lt;/li&gt;
&lt;li&gt;McFadden &lt;span class=&#34;math inline&#34;&gt;\(R^2_{McF}\)&lt;/span&gt;, and&lt;/li&gt;
&lt;li&gt;Tjur &lt;span class=&#34;math inline&#34;&gt;\(R^2_{T}\)&lt;/span&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The &lt;code&gt;tab_model()&lt;/code&gt; function gives the Tjur &lt;span class=&#34;math inline&#34;&gt;\(R^2_{T}\)&lt;/span&gt; by default.&lt;/p&gt;
&lt;p&gt;Based on the AIC and the Tjur &lt;span class=&#34;math inline&#34;&gt;\(R^2_{T}\)&lt;/span&gt;, the last model is considered as the best one among the 3 considered.&lt;/p&gt;
&lt;p&gt;Note that, even though a model is deemed the best one among the ones you have considered (based on one or several criteria), it does not necessarily mean that it fits the data well. There are several methods to check the quality of a model and to check if it is appropriate for the data at hand. This is the topic of the next section.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;quality-of-a-model&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Quality of a model&lt;/h2&gt;
&lt;p&gt;Usually, the goal of building a model is to be able to predict, as precisely as possible, the response variable for new data.&lt;/p&gt;
&lt;p&gt;In the next sections, we present some measures to judge the quality of a model, starting with the easiest and most intuitive one, followed by two widely used in the medical domain, and finally two other metrics common in the field of machine learning.&lt;/p&gt;
&lt;div id=&#34;validity-of-the-predictions&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Validity of the predictions&lt;/h3&gt;
&lt;div id=&#34;accuracy&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Accuracy&lt;/h4&gt;
&lt;p&gt;A good way to judge the accuracy of a model is to monitor its performance on new data and count how often it predicts the correct outcome.&lt;/p&gt;
&lt;p&gt;Unfortunately, when we have access to new data, we often do not know the real outcome and we cannot therefore check if the model does a good job in predicting the outcome. The trick is to:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;train the model on the initial data frame,&lt;/li&gt;
&lt;li&gt;test the model on the exact same data (just like if it was a complete different data frame for which we do not know the outcome), and then&lt;/li&gt;
&lt;li&gt;compare the predictions made by the model to the real outcomes.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;To illustrate this process, we take the model built in the previous section and test it on the initial data frame.&lt;/p&gt;
&lt;p&gt;Moreover, suppose that if the probability for the patient to develop a heart disease is below 50%, we consider that the predicted outcome is the absence of the disease, otherwise the predicted outcome is the presence of the disease.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# create a vector of predicted probabilities
preds &amp;lt;- predict(m5_final,
  newdata = select(dat, -heart_disease), # remove real outcomes
  type = &amp;quot;response&amp;quot;
)

# if probability &amp;lt; threshold, patient is considered not to have the disease
preds_outcome &amp;lt;- ifelse(preds &amp;lt; 0.5,
  0,
  1
)

# transform predictions into factor and set labels
preds_outcome &amp;lt;- factor(preds_outcome,
  levels = c(0, 1),
  labels = c(&amp;quot;no disease&amp;quot;, &amp;quot;disease&amp;quot;)
)

# compare observed vs. predicted outcome
tab &amp;lt;- table(dat$heart_disease, preds_outcome,
  dnn = c(&amp;quot;observed&amp;quot;, &amp;quot;predicted&amp;quot;)
)

# print results
tab&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             predicted
## observed     no disease disease
##   no disease        132      28
##   disease            33     104&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From the contingency table of the predicted and observed outcomes, we see that the model:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;correctly predicted the absence of the disease for 132 patients,&lt;/li&gt;
&lt;li&gt;incorrectly predicted the presence of the disease for 28 patients,&lt;/li&gt;
&lt;li&gt;incorrectly predicted the absence of the disease for 33 patients, and&lt;/li&gt;
&lt;li&gt;correctly predicted the presence of the disease for 104 patients.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The percentage of correct predictions, referred as the accuracy, is the sum of the correct predictions divided by the total number of predictions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;accuracy &amp;lt;- sum(diag(tab)) / sum(tab)
accuracy&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.7946128&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This model has an accuracy of 79.5%.&lt;/p&gt;
&lt;p&gt;Although accuracy is the most intuitive and easiest way to measure a model’s predictive performance, it has some drawbacks, notably because we have to choose an &lt;em&gt;arbitrary&lt;/em&gt; threshold beyond which we classify a new observation as 1 or 0. A more detailed discussion about this can be found on Frank Harrell’s &lt;a href=&#34;https://hbiostat.org/blog/post/classification/index.html&#34; target=&#34;_blank&#34;&gt;blog&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;In this illustration, we chose 50% as the threshold beyond which a patient was considered as having the disease. Nonetheless, we could have chosen another threshold and the results would have been different!&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;sensitivity-and-specificity&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Sensitivity and specificity&lt;/h4&gt;
&lt;p&gt;If you work in the medical field, or if your research is related to medical sciences, you have probably already heard about sensitivity and specificity.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;sensitivity&lt;/strong&gt; of a classifier, also referred as the recall, measures the ability of a classifier to detect the condition when the condition is present. In our case, it is the percentage of diseased people who are correctly identified as having the disease. Formally, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[ Sensitivity = \frac{\text{True positives}}{\text{True positives} + \text{False negatives}},\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where true positives are people correctly diagnosed as ill and false negatives are people incorrectly diagnosed as healthy.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;specificity&lt;/strong&gt; of a classifier measures the ability of a classifier to correctly exclude the condition when the condition is absent. In our case, it is the percentage of healthy people who are correctly identified as not having the disease. Formally, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[Specificity = \frac{\text{True negatives}}{\text{True negatives} + \text{False positives}},\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where true negatives are people correctly diagnosed as healthy and false positives are people incorrectly diagnosed as ill.&lt;/p&gt;
&lt;p&gt;In R, sensitivity and specificity can be computed as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# sensitivity
sensitivity &amp;lt;- tab[2, 2] / (tab[2, 2] + tab[2, 1])
sensitivity&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.7591241&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# specificity
specificity &amp;lt;- tab[1, 1] / (tab[1, 1] + tab[1, 2])
specificity&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.825&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With our model, we obtain:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;sensitivity = 75.9%, and&lt;/li&gt;
&lt;li&gt;specificity = 82.5%.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The closer the sensitivity and the specificity are to 100%, the better the model.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;auc-and-roc-curve&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;AUC and ROC curve&lt;/h3&gt;
&lt;p&gt;We have already seen that the better the quality of the model, the better the predictions.&lt;/p&gt;
&lt;p&gt;Another common and less arbitrary way to judge the quality of a model is by computing the AUC (Area Under the Curve) and plotting the ROC (Receiver Operating Characteristic) curve.&lt;/p&gt;
&lt;p&gt;This can be achieved easily thanks to the &lt;code&gt;{pROC}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load package
library(pROC)

# save roc object
res &amp;lt;- roc(heart_disease ~ fitted(m5_final),
  data = dat
)

# plot ROC curve
ggroc(res, legacy.axes = TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/index_files/figure-html/unnamed-chunk-42-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# print AUC
res$auc&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Area under the curve: 0.87&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As the &lt;code&gt;ggroc()&lt;/code&gt; function works with layers from the &lt;code&gt;{ggplot2}&lt;/code&gt; package, we can print the AUC directly in the title of the plot of the ROC curve:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# plot ROC curve with AUC in title
ggroc(res, legacy.axes = TRUE) +
  labs(title = paste0(&amp;quot;AUC = &amp;quot;, round(res$auc, 2)))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/index_files/figure-html/unnamed-chunk-43-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;These two quality metrics can be interpreted as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;in the plot, the closer the ROC curve is to the upper left-hand corner, the better the model, and&lt;/li&gt;
&lt;li&gt;the closer the AUC is to 1, the better the model.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Based on the ROC curve and the AUC, we can say that this model is good to very good. This means that the model is appropriate for these data, and that it can be useful to predict whether or not a patient will develop a heart disease!&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;reporting-results&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Reporting results&lt;/h2&gt;
&lt;p&gt;As we have seen before, odds ratios are useful when reporting results of binary logistic regressions.&lt;/p&gt;
&lt;p&gt;Computing these odds ratios together with the confidence intervals is not particularly difficult. However, presenting them in a table for a publication or a report can quickly become time consuming, in particular if you have many models and many independent variables.&lt;/p&gt;
&lt;p&gt;Luckily, there are two packages which saved me a lot of time and which I use almost every time I need to report results of a logistic regression.&lt;/p&gt;
&lt;p&gt;The first package, called &lt;code&gt;{gtsummary}&lt;/code&gt; is useful to report results of one regression at a time. The second one is the &lt;code&gt;{finalfit}&lt;/code&gt; package.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; This packages is more appropriate if you need to report results of several regressions at a time.&lt;/p&gt;
&lt;div id=&#34;gtsummary-package&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;{gtsummary} package&lt;/h3&gt;
&lt;p&gt;Here is an example with one of the models built previously:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load package
library(gtsummary)

# print table of results
tbl_regression(m5_final, exponentiate = TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;hsdigyayxw&#34; style=&#34;padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;&#34;&gt;
&lt;style&gt;#hsdigyayxw table {
  font-family: system-ui, &#39;Segoe UI&#39;, Roboto, Helvetica, Arial, sans-serif, &#39;Apple Color Emoji&#39;, &#39;Segoe UI Emoji&#39;, &#39;Segoe UI Symbol&#39;, &#39;Noto Color Emoji&#39;;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

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

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

#hsdigyayxw .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;
}

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

#hsdigyayxw .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;
}

#hsdigyayxw .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;
}

#hsdigyayxw .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;
}

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

#hsdigyayxw .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;
}

#hsdigyayxw .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;
}

#hsdigyayxw .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;
}

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

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

#hsdigyayxw .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%;
}

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

#hsdigyayxw .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;
}

#hsdigyayxw .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;
}

#hsdigyayxw .gt_from_md &gt; :first-child {
  margin-top: 0;
}

#hsdigyayxw .gt_from_md &gt; :last-child {
  margin-bottom: 0;
}

#hsdigyayxw .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;
}

#hsdigyayxw .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;
}

#hsdigyayxw .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;
}

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

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

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

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

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

#hsdigyayxw .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;
}

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

#hsdigyayxw .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;
}

#hsdigyayxw .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;
}

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

#hsdigyayxw .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;
}

#hsdigyayxw .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;
}

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

#hsdigyayxw .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;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#hsdigyayxw div.Reactable &gt; div.rt-table &gt; div.rt-thead &gt; div.rt-tr.rt-tr-group-header &gt; div.rt-th-group:after {
  height: 0px !important;
}
&lt;/style&gt;
&lt;table class=&#34;gt_table&#34; data-quarto-disable-processing=&#34;false&#34; data-quarto-bootstrap=&#34;false&#34;&gt;
  &lt;thead&gt;
    &lt;tr class=&#34;gt_col_headings&#34;&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;label&#34;&gt;&lt;span class=&#39;gt_from_md&#39;&gt;&lt;strong&gt;Characteristic&lt;/strong&gt;&lt;/span&gt;&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_center&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;estimate&#34;&gt;&lt;span class=&#39;gt_from_md&#39;&gt;&lt;strong&gt;OR&lt;/strong&gt;&lt;/span&gt;&lt;span class=&#34;gt_footnote_marks&#34; style=&#34;white-space:nowrap;font-style:italic;font-weight:normal;line-height:0;&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/span&gt;&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_center&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;conf.low&#34;&gt;&lt;span class=&#39;gt_from_md&#39;&gt;&lt;strong&gt;95% CI&lt;/strong&gt;&lt;/span&gt;&lt;span class=&#34;gt_footnote_marks&#34; style=&#34;white-space:nowrap;font-style:italic;font-weight:normal;line-height:0;&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/span&gt;&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_center&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;p.value&#34;&gt;&lt;span class=&#39;gt_from_md&#39;&gt;&lt;strong&gt;p-value&lt;/strong&gt;&lt;/span&gt;&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody class=&#34;gt_table_body&#34;&gt;
    &lt;tr&gt;&lt;td headers=&#34;label&#34; class=&#34;gt_row gt_left&#34;&gt;age&lt;/td&gt;
&lt;td headers=&#34;estimate&#34; class=&#34;gt_row gt_center&#34;&gt;0.74&lt;/td&gt;
&lt;td headers=&#34;conf.low&#34; class=&#34;gt_row gt_center&#34;&gt;0.55, 0.96&lt;/td&gt;
&lt;td headers=&#34;p.value&#34; class=&#34;gt_row gt_center&#34;&gt;0.031&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;label&#34; class=&#34;gt_row gt_left&#34;&gt;sex&lt;/td&gt;
&lt;td headers=&#34;estimate&#34; class=&#34;gt_row gt_center&#34;&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td headers=&#34;conf.low&#34; class=&#34;gt_row gt_center&#34;&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td headers=&#34;p.value&#34; class=&#34;gt_row gt_center&#34;&gt;&lt;br /&gt;&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;label&#34; class=&#34;gt_row gt_left&#34;&gt;    female&lt;/td&gt;
&lt;td headers=&#34;estimate&#34; class=&#34;gt_row gt_center&#34;&gt;—&lt;/td&gt;
&lt;td headers=&#34;conf.low&#34; class=&#34;gt_row gt_center&#34;&gt;—&lt;/td&gt;
&lt;td headers=&#34;p.value&#34; class=&#34;gt_row gt_center&#34;&gt;&lt;br /&gt;&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;label&#34; class=&#34;gt_row gt_left&#34;&gt;    male&lt;/td&gt;
&lt;td headers=&#34;estimate&#34; class=&#34;gt_row gt_center&#34;&gt;5.50&lt;/td&gt;
&lt;td headers=&#34;conf.low&#34; class=&#34;gt_row gt_center&#34;&gt;2.82, 11.2&lt;/td&gt;
&lt;td headers=&#34;p.value&#34; class=&#34;gt_row gt_center&#34;&gt;&lt;0.001&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;label&#34; class=&#34;gt_row gt_left&#34;&gt;chest_pain&lt;/td&gt;
&lt;td headers=&#34;estimate&#34; class=&#34;gt_row gt_center&#34;&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td headers=&#34;conf.low&#34; class=&#34;gt_row gt_center&#34;&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td headers=&#34;p.value&#34; class=&#34;gt_row gt_center&#34;&gt;&lt;br /&gt;&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;label&#34; class=&#34;gt_row gt_left&#34;&gt;    typical angina&lt;/td&gt;
&lt;td headers=&#34;estimate&#34; class=&#34;gt_row gt_center&#34;&gt;—&lt;/td&gt;
&lt;td headers=&#34;conf.low&#34; class=&#34;gt_row gt_center&#34;&gt;—&lt;/td&gt;
&lt;td headers=&#34;p.value&#34; class=&#34;gt_row gt_center&#34;&gt;&lt;br /&gt;&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;label&#34; class=&#34;gt_row gt_left&#34;&gt;    atypical angina&lt;/td&gt;
&lt;td headers=&#34;estimate&#34; class=&#34;gt_row gt_center&#34;&gt;0.99&lt;/td&gt;
&lt;td headers=&#34;conf.low&#34; class=&#34;gt_row gt_center&#34;&gt;0.27, 3.65&lt;/td&gt;
&lt;td headers=&#34;p.value&#34; class=&#34;gt_row gt_center&#34;&gt;&gt;0.9&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;label&#34; class=&#34;gt_row gt_left&#34;&gt;    non-anginal pain&lt;/td&gt;
&lt;td headers=&#34;estimate&#34; class=&#34;gt_row gt_center&#34;&gt;0.94&lt;/td&gt;
&lt;td headers=&#34;conf.low&#34; class=&#34;gt_row gt_center&#34;&gt;0.30, 3.07&lt;/td&gt;
&lt;td headers=&#34;p.value&#34; class=&#34;gt_row gt_center&#34;&gt;&gt;0.9&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;label&#34; class=&#34;gt_row gt_left&#34;&gt;    asymptomatic&lt;/td&gt;
&lt;td headers=&#34;estimate&#34; class=&#34;gt_row gt_center&#34;&gt;7.19&lt;/td&gt;
&lt;td headers=&#34;conf.low&#34; class=&#34;gt_row gt_center&#34;&gt;2.44, 22.8&lt;/td&gt;
&lt;td headers=&#34;p.value&#34; class=&#34;gt_row gt_center&#34;&gt;&lt;0.001&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;label&#34; class=&#34;gt_row gt_left&#34;&gt;max_heartrate&lt;/td&gt;
&lt;td headers=&#34;estimate&#34; class=&#34;gt_row gt_center&#34;&gt;0.85&lt;/td&gt;
&lt;td headers=&#34;conf.low&#34; class=&#34;gt_row gt_center&#34;&gt;0.76, 0.94&lt;/td&gt;
&lt;td headers=&#34;p.value&#34; class=&#34;gt_row gt_center&#34;&gt;0.003&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;label&#34; class=&#34;gt_row gt_left&#34;&gt;age * max_heartrate&lt;/td&gt;
&lt;td headers=&#34;estimate&#34; class=&#34;gt_row gt_center&#34;&gt;1.00&lt;/td&gt;
&lt;td headers=&#34;conf.low&#34; class=&#34;gt_row gt_center&#34;&gt;1.00, 1.00&lt;/td&gt;
&lt;td headers=&#34;p.value&#34; class=&#34;gt_row gt_center&#34;&gt;0.013&lt;/td&gt;&lt;/tr&gt;
  &lt;/tbody&gt;
  
  &lt;tfoot class=&#34;gt_footnotes&#34;&gt;
    &lt;tr&gt;
      &lt;td class=&#34;gt_footnote&#34; colspan=&#34;4&#34;&gt;&lt;span class=&#34;gt_footnote_marks&#34; style=&#34;white-space:nowrap;font-style:italic;font-weight:normal;line-height:0;&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/span&gt; &lt;span class=&#39;gt_from_md&#39;&gt;OR = Odds Ratio, CI = Confidence Interval&lt;/span&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tfoot&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;What I like with this package is its ease of use, and the fact that all results are nicely formatted in a table. This is a very good starting point when I need to create a table for a publication or a report, for one regression at a time.&lt;/p&gt;
&lt;p&gt;The second package becomes interesting when you need to report results for several models at once.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;finalfit-package&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;{finalfit} package&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;{finalfit}&lt;/code&gt; package allows to report odds ratios, their confidence intervals and the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values in a very efficient way. Moreover, it is quite easy to do so for many regressions at the same time.&lt;/p&gt;
&lt;p&gt;Let me present the package by reporting results of:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;all univariable binary logistic regressions that are possible with the variables available in the data frame,&lt;/li&gt;
&lt;li&gt;a multivariable binary logistic regression that includes all variables available in the data frame, and&lt;/li&gt;
&lt;li&gt;a multivariable binary logistic regression that includes only some of the variables present in the data frame.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We start with all the possible univariable binary logistic regressions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load packages
library(tidyverse)
library(gt)
library(finalfit)

# set dependent and independent variables
dependent &amp;lt;- &amp;quot;heart_disease&amp;quot;
independent &amp;lt;- c(&amp;quot;age&amp;quot;, &amp;quot;sex&amp;quot;, &amp;quot;chest_pain&amp;quot;, &amp;quot;max_heartrate&amp;quot;)

# save results of univariable logistic regressions
glmuni &amp;lt;- dat |&amp;gt;
  glmuni(dependent, independent) |&amp;gt;
  fit2df(
    explanatory_name = &amp;quot;Variables&amp;quot;,
    estimate_name = &amp;quot;Crude OR&amp;quot;,
    estimate_suffix = &amp;quot; (95% CI)&amp;quot;
  )

# print results
glmuni |&amp;gt;
  gt()&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;ewvlblrgtf&#34; style=&#34;padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;&#34;&gt;
&lt;style&gt;#ewvlblrgtf table {
  font-family: system-ui, &#39;Segoe UI&#39;, Roboto, Helvetica, Arial, sans-serif, &#39;Apple Color Emoji&#39;, &#39;Segoe UI Emoji&#39;, &#39;Segoe UI Symbol&#39;, &#39;Noto Color Emoji&#39;;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

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

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

#ewvlblrgtf .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;
}

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

#ewvlblrgtf .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;
}

#ewvlblrgtf .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;
}

#ewvlblrgtf .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;
}

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

#ewvlblrgtf .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;
}

#ewvlblrgtf .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;
}

#ewvlblrgtf .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;
}

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

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

#ewvlblrgtf .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%;
}

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

#ewvlblrgtf .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;
}

#ewvlblrgtf .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;
}

#ewvlblrgtf .gt_from_md &gt; :first-child {
  margin-top: 0;
}

#ewvlblrgtf .gt_from_md &gt; :last-child {
  margin-bottom: 0;
}

#ewvlblrgtf .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;
}

#ewvlblrgtf .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;
}

#ewvlblrgtf .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;
}

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

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

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

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

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

#ewvlblrgtf .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;
}

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

#ewvlblrgtf .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;
}

#ewvlblrgtf .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;
}

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

#ewvlblrgtf .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;
}

#ewvlblrgtf .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;
}

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

#ewvlblrgtf .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;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#ewvlblrgtf div.Reactable &gt; div.rt-table &gt; div.rt-thead &gt; div.rt-tr.rt-tr-group-header &gt; div.rt-th-group:after {
  height: 0px !important;
}
&lt;/style&gt;
&lt;table class=&#34;gt_table&#34; data-quarto-disable-processing=&#34;false&#34; data-quarto-bootstrap=&#34;false&#34;&gt;
  &lt;thead&gt;
    &lt;tr class=&#34;gt_col_headings&#34;&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;Variables&#34;&gt;Variables&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;Crude-OR-(95%-CI)&#34;&gt;Crude OR (95% CI)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody class=&#34;gt_table_body&#34;&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;age&lt;/td&gt;
&lt;td headers=&#34;Crude OR (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;1.05 (1.03-1.08, p&amp;lt;0.001)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;sexmale&lt;/td&gt;
&lt;td headers=&#34;Crude OR (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;3.57 (2.12-6.18, p&amp;lt;0.001)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;chest_painatypical angina&lt;/td&gt;
&lt;td headers=&#34;Crude OR (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;0.51 (0.16-1.66, p=0.255)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;chest_painnon-anginal pain&lt;/td&gt;
&lt;td headers=&#34;Crude OR (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;0.63 (0.23-1.86, p=0.384)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;chest_painasymptomatic&lt;/td&gt;
&lt;td headers=&#34;Crude OR (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;6.04 (2.39-16.76, p&amp;lt;0.001)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;max_heartrate&lt;/td&gt;
&lt;td headers=&#34;Crude OR (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;0.96 (0.94-0.97, p&amp;lt;0.001)&lt;/td&gt;&lt;/tr&gt;
  &lt;/tbody&gt;
  
  
&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;A few remarks regarding this code:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;glmuni()&lt;/code&gt; is used because we want to run univariable GLM.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;explanatory_name = &#34;Variables&#34;&lt;/code&gt; is used to rename the first column (by default it is “explanatory”).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;estimate_name = &#34;Crude OR&#34;&lt;/code&gt; is used to rename the second column and inform the reader that we are in the univariable case. In the univariable case, OR are often called crude OR because they are not adjusted for the effects of the other independent variables.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;estimate_suffix = &#34; (95% CI)&#34;&lt;/code&gt; is used to specify that it is the 95% confidence intervals which are inside the parentheses.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;gt()&lt;/code&gt; layer at the end of the code is not compulsory. It is just to make the output appears in a nice table instead of the usual format of R outputs. See more information about the &lt;code&gt;{gt}&lt;/code&gt; package in its &lt;a href=&#34;https://gt.rstudio.com/&#34; target=&#34;_blank&#34;&gt;documentation&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here is how to report results of a multivariable binary logistic regression which includes all variables:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# save results of full model
glmmulti_full &amp;lt;- dat |&amp;gt;
  glmmulti(dependent, independent) |&amp;gt;
  fit2df(
    explanatory_name = &amp;quot;Variables&amp;quot;,
    estimate_name = &amp;quot;Adjusted OR - full model&amp;quot;,
  )

# print results
glmmulti_full |&amp;gt;
  gt()&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;vtrqkpqzfa&#34; style=&#34;padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;&#34;&gt;
&lt;style&gt;#vtrqkpqzfa table {
  font-family: system-ui, &#39;Segoe UI&#39;, Roboto, Helvetica, Arial, sans-serif, &#39;Apple Color Emoji&#39;, &#39;Segoe UI Emoji&#39;, &#39;Segoe UI Symbol&#39;, &#39;Noto Color Emoji&#39;;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

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

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

#vtrqkpqzfa .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;
}

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

#vtrqkpqzfa .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;
}

#vtrqkpqzfa .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;
}

#vtrqkpqzfa .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;
}

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

#vtrqkpqzfa .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;
}

#vtrqkpqzfa .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;
}

#vtrqkpqzfa .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;
}

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

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

#vtrqkpqzfa .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%;
}

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

#vtrqkpqzfa .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;
}

#vtrqkpqzfa .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;
}

#vtrqkpqzfa .gt_from_md &gt; :first-child {
  margin-top: 0;
}

#vtrqkpqzfa .gt_from_md &gt; :last-child {
  margin-bottom: 0;
}

#vtrqkpqzfa .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;
}

#vtrqkpqzfa .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;
}

#vtrqkpqzfa .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;
}

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

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

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

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

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

#vtrqkpqzfa .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;
}

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

#vtrqkpqzfa .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;
}

#vtrqkpqzfa .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;
}

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

#vtrqkpqzfa .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;
}

#vtrqkpqzfa .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;
}

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

#vtrqkpqzfa .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;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#vtrqkpqzfa div.Reactable &gt; div.rt-table &gt; div.rt-thead &gt; div.rt-tr.rt-tr-group-header &gt; div.rt-th-group:after {
  height: 0px !important;
}
&lt;/style&gt;
&lt;table class=&#34;gt_table&#34; data-quarto-disable-processing=&#34;false&#34; data-quarto-bootstrap=&#34;false&#34;&gt;
  &lt;thead&gt;
    &lt;tr class=&#34;gt_col_headings&#34;&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;Variables&#34;&gt;Variables&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;Adjusted-OR---full-model&#34;&gt;Adjusted OR - full model&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody class=&#34;gt_table_body&#34;&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;age&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - full model&#34; class=&#34;gt_row gt_left&#34;&gt;1.04 (1.01-1.08, p=0.024)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;sexmale&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - full model&#34; class=&#34;gt_row gt_left&#34;&gt;5.40 (2.78-10.97, p&amp;lt;0.001)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;chest_painatypical angina&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - full model&#34; class=&#34;gt_row gt_left&#34;&gt;0.89 (0.25-3.19, p=0.851)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;chest_painnon-anginal pain&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - full model&#34; class=&#34;gt_row gt_left&#34;&gt;0.88 (0.29-2.81, p=0.828)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;chest_painasymptomatic&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - full model&#34; class=&#34;gt_row gt_left&#34;&gt;7.13 (2.51-22.03, p&amp;lt;0.001)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;max_heartrate&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - full model&#34; class=&#34;gt_row gt_left&#34;&gt;0.97 (0.95-0.99, p&amp;lt;0.001)&lt;/td&gt;&lt;/tr&gt;
  &lt;/tbody&gt;
  
  
&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;A few remarks regarding this code:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;glmmulti()&lt;/code&gt; is used because we want to run multivariable GLM.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;estimate_name = &#34;Adjusted OR - full model&#34;&lt;/code&gt; is used to remind the reader that we are in the multivariable case with all variables included. In the multivariable case, OR are often called adjusted OR because they are adjusted for the effects of the other independent variables.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here is how to report results of a multivariable binary logistic regression which includes only a selection of variables:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# select the variables to be included in the final model
independent_final &amp;lt;- c(&amp;quot;age&amp;quot;, &amp;quot;sex&amp;quot;, &amp;quot;chest_pain&amp;quot;)

# save results of final model
glmmulti_final &amp;lt;- dat |&amp;gt;
  glmmulti(dependent, independent_final) |&amp;gt;
  fit2df(
    explanatory_name = &amp;quot;Variables&amp;quot;,
    estimate_name = &amp;quot;Adjusted OR - final model&amp;quot;,
    estimate_suffix = &amp;quot; (95% CI)&amp;quot;
  )

# print results
glmmulti_final |&amp;gt;
  gt()&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;klgxvctcfp&#34; style=&#34;padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;&#34;&gt;
&lt;style&gt;#klgxvctcfp table {
  font-family: system-ui, &#39;Segoe UI&#39;, Roboto, Helvetica, Arial, sans-serif, &#39;Apple Color Emoji&#39;, &#39;Segoe UI Emoji&#39;, &#39;Segoe UI Symbol&#39;, &#39;Noto Color Emoji&#39;;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

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

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

#klgxvctcfp .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;
}

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

#klgxvctcfp .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;
}

#klgxvctcfp .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;
}

#klgxvctcfp .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;
}

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

#klgxvctcfp .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;
}

#klgxvctcfp .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;
}

#klgxvctcfp .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;
}

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

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

#klgxvctcfp .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%;
}

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

#klgxvctcfp .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;
}

#klgxvctcfp .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;
}

#klgxvctcfp .gt_from_md &gt; :first-child {
  margin-top: 0;
}

#klgxvctcfp .gt_from_md &gt; :last-child {
  margin-bottom: 0;
}

#klgxvctcfp .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;
}

#klgxvctcfp .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;
}

#klgxvctcfp .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;
}

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

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

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

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

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

#klgxvctcfp .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;
}

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

#klgxvctcfp .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;
}

#klgxvctcfp .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;
}

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

#klgxvctcfp .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;
}

#klgxvctcfp .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;
}

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

#klgxvctcfp .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;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#klgxvctcfp div.Reactable &gt; div.rt-table &gt; div.rt-thead &gt; div.rt-tr.rt-tr-group-header &gt; div.rt-th-group:after {
  height: 0px !important;
}
&lt;/style&gt;
&lt;table class=&#34;gt_table&#34; data-quarto-disable-processing=&#34;false&#34; data-quarto-bootstrap=&#34;false&#34;&gt;
  &lt;thead&gt;
    &lt;tr class=&#34;gt_col_headings&#34;&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;Variables&#34;&gt;Variables&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;Adjusted-OR---final-model-(95%-CI)&#34;&gt;Adjusted OR - final model (95% CI)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody class=&#34;gt_table_body&#34;&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;age&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - final model (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;1.07 (1.03-1.11, p&amp;lt;0.001)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;sexmale&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - final model (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;5.52 (2.88-11.07, p&amp;lt;0.001)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;chest_painatypical angina&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - final model (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;0.82 (0.24-2.82, p=0.743)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;chest_painnon-anginal pain&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - final model (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;0.93 (0.32-2.90, p=0.903)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;chest_painasymptomatic&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - final model (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;9.48 (3.47-28.53, p&amp;lt;0.001)&lt;/td&gt;&lt;/tr&gt;
  &lt;/tbody&gt;
  
  
&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Note that you have to manually select the variables (the package will not choose for you unfortunately). The selection could be done preliminary thanks to a stepwise procedure for example.&lt;/p&gt;
&lt;p&gt;Now the most interesting part of this package:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;we can combine all these results together,&lt;/li&gt;
&lt;li&gt;in addition to some descriptive statistics for each level of the dependent variable!&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here are all results combined together and displayed in a table:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# save descriptive statistics
summary &amp;lt;- dat |&amp;gt;
  summary_factorlist(dependent, independent, fit_id = TRUE)

# save results of regressions
output &amp;lt;- summary |&amp;gt;
  finalfit_merge(glmuni) |&amp;gt;
  finalfit_merge(glmmulti_full) |&amp;gt;
  finalfit_merge(glmmulti_final)

# print all results
output |&amp;gt;
  dplyr::select(-fit_id, -index) |&amp;gt;
  dplyr::rename(
    Variables = label,
    &amp;quot; &amp;quot; = levels
  ) |&amp;gt;
  gt()&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;szrjblstrk&#34; style=&#34;padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;&#34;&gt;
&lt;style&gt;#szrjblstrk table {
  font-family: system-ui, &#39;Segoe UI&#39;, Roboto, Helvetica, Arial, sans-serif, &#39;Apple Color Emoji&#39;, &#39;Segoe UI Emoji&#39;, &#39;Segoe UI Symbol&#39;, &#39;Noto Color Emoji&#39;;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

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

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

#szrjblstrk .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;
}

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

#szrjblstrk .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;
}

#szrjblstrk .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;
}

#szrjblstrk .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;
}

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

#szrjblstrk .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;
}

#szrjblstrk .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;
}

#szrjblstrk .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;
}

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

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

#szrjblstrk .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%;
}

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

#szrjblstrk .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;
}

#szrjblstrk .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;
}

#szrjblstrk .gt_from_md &gt; :first-child {
  margin-top: 0;
}

#szrjblstrk .gt_from_md &gt; :last-child {
  margin-bottom: 0;
}

#szrjblstrk .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;
}

#szrjblstrk .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;
}

#szrjblstrk .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;
}

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

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

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

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

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

#szrjblstrk .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;
}

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

#szrjblstrk .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;
}

#szrjblstrk .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;
}

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

#szrjblstrk .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;
}

#szrjblstrk .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;
}

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

#szrjblstrk .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;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#szrjblstrk div.Reactable &gt; div.rt-table &gt; div.rt-thead &gt; div.rt-tr.rt-tr-group-header &gt; div.rt-th-group:after {
  height: 0px !important;
}
&lt;/style&gt;
&lt;table class=&#34;gt_table&#34; data-quarto-disable-processing=&#34;false&#34; data-quarto-bootstrap=&#34;false&#34;&gt;
  &lt;thead&gt;
    &lt;tr class=&#34;gt_col_headings&#34;&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;Variables&#34;&gt;Variables&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;a-&#34;&gt; &lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;no-disease&#34;&gt;no disease&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;disease&#34;&gt;disease&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;Crude-OR-(95%-CI)&#34;&gt;Crude OR (95% CI)&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;Adjusted-OR---full-model&#34;&gt;Adjusted OR - full model&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;Adjusted-OR---final-model-(95%-CI)&#34;&gt;Adjusted OR - final model (95% CI)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody class=&#34;gt_table_body&#34;&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;age&lt;/td&gt;
&lt;td headers=&#34; &#34; class=&#34;gt_row gt_left&#34;&gt;Mean (SD)&lt;/td&gt;
&lt;td headers=&#34;no disease&#34; class=&#34;gt_row gt_right&#34;&gt;52.6 (9.6)&lt;/td&gt;
&lt;td headers=&#34;disease&#34; class=&#34;gt_row gt_right&#34;&gt;56.8 (7.9)&lt;/td&gt;
&lt;td headers=&#34;Crude OR (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;1.05 (1.03-1.08, p&amp;lt;0.001)&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - full model&#34; class=&#34;gt_row gt_left&#34;&gt;1.04 (1.01-1.08, p=0.024)&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - final model (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;1.07 (1.03-1.11, p&amp;lt;0.001)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;sex&lt;/td&gt;
&lt;td headers=&#34; &#34; class=&#34;gt_row gt_left&#34;&gt;female&lt;/td&gt;
&lt;td headers=&#34;no disease&#34; class=&#34;gt_row gt_right&#34;&gt;71 (44.4)&lt;/td&gt;
&lt;td headers=&#34;disease&#34; class=&#34;gt_row gt_right&#34;&gt;25 (18.2)&lt;/td&gt;
&lt;td headers=&#34;Crude OR (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;-&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - full model&#34; class=&#34;gt_row gt_left&#34;&gt;-&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - final model (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;-&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;&lt;/td&gt;
&lt;td headers=&#34; &#34; class=&#34;gt_row gt_left&#34;&gt;male&lt;/td&gt;
&lt;td headers=&#34;no disease&#34; class=&#34;gt_row gt_right&#34;&gt;89 (55.6)&lt;/td&gt;
&lt;td headers=&#34;disease&#34; class=&#34;gt_row gt_right&#34;&gt;112 (81.8)&lt;/td&gt;
&lt;td headers=&#34;Crude OR (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;3.57 (2.12-6.18, p&amp;lt;0.001)&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - full model&#34; class=&#34;gt_row gt_left&#34;&gt;5.40 (2.78-10.97, p&amp;lt;0.001)&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - final model (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;5.52 (2.88-11.07, p&amp;lt;0.001)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;chest_pain&lt;/td&gt;
&lt;td headers=&#34; &#34; class=&#34;gt_row gt_left&#34;&gt;typical angina&lt;/td&gt;
&lt;td headers=&#34;no disease&#34; class=&#34;gt_row gt_right&#34;&gt;16 (10.0)&lt;/td&gt;
&lt;td headers=&#34;disease&#34; class=&#34;gt_row gt_right&#34;&gt;7 (5.1)&lt;/td&gt;
&lt;td headers=&#34;Crude OR (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;-&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - full model&#34; class=&#34;gt_row gt_left&#34;&gt;-&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - final model (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;-&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;&lt;/td&gt;
&lt;td headers=&#34; &#34; class=&#34;gt_row gt_left&#34;&gt;atypical angina&lt;/td&gt;
&lt;td headers=&#34;no disease&#34; class=&#34;gt_row gt_right&#34;&gt;40 (25.0)&lt;/td&gt;
&lt;td headers=&#34;disease&#34; class=&#34;gt_row gt_right&#34;&gt;9 (6.6)&lt;/td&gt;
&lt;td headers=&#34;Crude OR (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;0.51 (0.16-1.66, p=0.255)&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - full model&#34; class=&#34;gt_row gt_left&#34;&gt;0.89 (0.25-3.19, p=0.851)&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - final model (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;0.82 (0.24-2.82, p=0.743)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;&lt;/td&gt;
&lt;td headers=&#34; &#34; class=&#34;gt_row gt_left&#34;&gt;non-anginal pain&lt;/td&gt;
&lt;td headers=&#34;no disease&#34; class=&#34;gt_row gt_right&#34;&gt;65 (40.6)&lt;/td&gt;
&lt;td headers=&#34;disease&#34; class=&#34;gt_row gt_right&#34;&gt;18 (13.1)&lt;/td&gt;
&lt;td headers=&#34;Crude OR (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;0.63 (0.23-1.86, p=0.384)&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - full model&#34; class=&#34;gt_row gt_left&#34;&gt;0.88 (0.29-2.81, p=0.828)&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - final model (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;0.93 (0.32-2.90, p=0.903)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;&lt;/td&gt;
&lt;td headers=&#34; &#34; class=&#34;gt_row gt_left&#34;&gt;asymptomatic&lt;/td&gt;
&lt;td headers=&#34;no disease&#34; class=&#34;gt_row gt_right&#34;&gt;39 (24.4)&lt;/td&gt;
&lt;td headers=&#34;disease&#34; class=&#34;gt_row gt_right&#34;&gt;103 (75.2)&lt;/td&gt;
&lt;td headers=&#34;Crude OR (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;6.04 (2.39-16.76, p&amp;lt;0.001)&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - full model&#34; class=&#34;gt_row gt_left&#34;&gt;7.13 (2.51-22.03, p&amp;lt;0.001)&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - final model (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;9.48 (3.47-28.53, p&amp;lt;0.001)&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Variables&#34; class=&#34;gt_row gt_left&#34;&gt;max_heartrate&lt;/td&gt;
&lt;td headers=&#34; &#34; class=&#34;gt_row gt_left&#34;&gt;Mean (SD)&lt;/td&gt;
&lt;td headers=&#34;no disease&#34; class=&#34;gt_row gt_right&#34;&gt;158.6 (19.0)&lt;/td&gt;
&lt;td headers=&#34;disease&#34; class=&#34;gt_row gt_right&#34;&gt;139.1 (22.7)&lt;/td&gt;
&lt;td headers=&#34;Crude OR (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;0.96 (0.94-0.97, p&amp;lt;0.001)&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - full model&#34; class=&#34;gt_row gt_left&#34;&gt;0.97 (0.95-0.99, p&amp;lt;0.001)&lt;/td&gt;
&lt;td headers=&#34;Adjusted OR - final model (95% CI)&#34; class=&#34;gt_row gt_left&#34;&gt;-&lt;/td&gt;&lt;/tr&gt;
  &lt;/tbody&gt;
  
  
&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;A few remarks regarding this code:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;summary_factorlist(dependent, independent, fit_id = TRUE)&lt;/code&gt; is used to compute the descriptive statistics by group of the dependent variable.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;finalfit_merge()&lt;/code&gt; is used to merge results together.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dplyr::select(-fit_id, -index)&lt;/code&gt; is used to remove unnecessary columns.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dplyr::rename(Variables = label, &#34; &#34; = levels)&lt;/code&gt; is used to renames some columns.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;And finally, a few remarks regarding the resulting table:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The first column gives the name of the variables.&lt;/li&gt;
&lt;li&gt;The second column specifies:
&lt;ul&gt;
&lt;li&gt;for qualitative variables: the levels&lt;/li&gt;
&lt;li&gt;for quantitative variables: that it is the mean and the standard deviation (SD) which will be computed in the next two columns&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;The third and fourth columns give the descriptive statistics for each level of the dependent variable:
&lt;ul&gt;
&lt;li&gt;for qualitative variables: the number of cases, and in parentheses the frequencies by column&lt;/li&gt;
&lt;li&gt;for quantitative variables: the mean, and in parentheses the standard deviation&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;The last three columns give the OR, and in parentheses the 95% CI of the OR and the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value (for the univariable and the two multivariable models, respectively).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For your convenience, here is the full code so you can copy paste it easily in case you want to reproduce the process:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load packages
library(tidyverse)
library(gt)
library(finalfit)

# set variables
dependent &amp;lt;- &amp;quot;heart_disease&amp;quot;
independent &amp;lt;- c(&amp;quot;age&amp;quot;, &amp;quot;sex&amp;quot;, &amp;quot;chest_pain&amp;quot;, &amp;quot;max_heartrate&amp;quot;)
independent_final &amp;lt;- c(&amp;quot;age&amp;quot;, &amp;quot;sex&amp;quot;, &amp;quot;chest_pain&amp;quot;)

# save descriptive statistics
summary &amp;lt;- dat |&amp;gt;
  summary_factorlist(dependent, independent, fit_id = TRUE)

# save results of univariable logistic regressions
glmuni &amp;lt;- dat |&amp;gt;
  glmuni(dependent, independent) |&amp;gt;
  fit2df(
    explanatory_name = &amp;quot;Variables&amp;quot;,
    estimate_name = &amp;quot;Crude OR&amp;quot;,
    estimate_suffix = &amp;quot; (95% CI)&amp;quot;
  )

# save results of full model
glmmulti_full &amp;lt;- dat |&amp;gt;
  glmmulti(dependent, independent) |&amp;gt;
  fit2df(
    explanatory_name = &amp;quot;Variables&amp;quot;,
    estimate_name = &amp;quot;Adjusted OR - full model&amp;quot;,
  )

# save results of final model
glmmulti_final &amp;lt;- dat |&amp;gt;
  glmmulti(dependent, independent_final) |&amp;gt;
  fit2df(
    explanatory_name = &amp;quot;Variables&amp;quot;,
    estimate_name = &amp;quot;Adjusted OR - final model&amp;quot;,
    estimate_suffix = &amp;quot; (95% CI)&amp;quot;
  )

# save merged results
output &amp;lt;- summary |&amp;gt;
  finalfit_merge(glmuni) |&amp;gt;
  finalfit_merge(glmmulti_full) |&amp;gt;
  finalfit_merge(glmmulti_final)

# print all results
output |&amp;gt;
  dplyr::select(-fit_id, -index) |&amp;gt;
  dplyr::rename(
    Variables = label,
    &amp;quot; &amp;quot; = levels
  ) |&amp;gt;
  gt()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Last but not least, the &lt;code&gt;or_plot()&lt;/code&gt; function, also available from the &lt;code&gt;{finalfit}&lt;/code&gt; package, is useful to visualize all odds ratio and their 95% confidence intervals:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat |&amp;gt; or_plot(dependent, independent,
  table_text_size = 3.5 # reduce text size
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/index_files/figure-html/unnamed-chunk-50-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Here is how to read this plot:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The squares represent the OR, and the whiskers their 95% CI.&lt;/li&gt;
&lt;li&gt;When the 95% CI crosses the vertical dashed line, it means that the OR is not significantly different from 1 (at the 5% significance level). In these cases, we cannot reject the hypothesis of no association with the dependent variable.&lt;/li&gt;
&lt;li&gt;When the 95% CI does not cross the vertical dashed line, it means that the OR is significantly different from 1. In these cases:
&lt;ul&gt;
&lt;li&gt;if the square is located to the right of the vertical dashed line, there is a positive relationship between the outcome and the independent variable (known as a risk factor), and&lt;/li&gt;
&lt;li&gt;if the square is located to the left of the vertical dashed line, there is a negative relationship between the outcome and the independent variable (known as a protective factor).&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The plot confirms what was obtained above:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;age is a risk factor for heart disease,&lt;/li&gt;
&lt;li&gt;maximum heart rate achieved is a protective factor for heart disease, and&lt;/li&gt;
&lt;li&gt;being a male and suffering from asymptomatic chest pain are both risk factors of heart disease.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Be careful that sometimes the square is too big to see the whiskers of the 95% CI. This is the case for the variables &lt;code&gt;max_heartrate&lt;/code&gt; and &lt;code&gt;age&lt;/code&gt;. In these cases, it is better to check the significance of the OR thanks to their 95% CI or the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values printed in parentheses.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conditions-of-application&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Conditions of application&lt;/h2&gt;
&lt;p&gt;For results to be valid and interpretable, a binary logistic regression requires:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;the dependent variable to be binary,&lt;/li&gt;
&lt;li&gt;independence of the observations: no repeated measurements or matched data, otherwise generalize linear mixed effect models (GLMM) should be used,&lt;/li&gt;
&lt;li&gt;linearity of continuous independent variables and the log-odds outcome: take age and heart disease as an example. If heart disease is more frequent or less frequent as age rises, the model will work well. However, if children and the elderly are at high risk of having a heart disease, but those in middle years are not, then the relationship is not linear, or not monotonic, meaning that the response does not only go in one direction,&lt;/li&gt;
&lt;li&gt;a sufficiently large sample size (for confidence intervals and hypothesis tests to be valid), and&lt;/li&gt;
&lt;li&gt;no multicollinearity: independent variables should not be highly correlated with each other, otherwise coefficients and OR can become unstable.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Here is how to verify each of them:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;this is obvious; check if the dependent variable has indeed only two levels,&lt;/li&gt;
&lt;li&gt;this is often not tested formally, but verified through the design of the experiment,&lt;/li&gt;
&lt;li&gt;quantitative independent variables should have a linear relationship between their log-odds and their observed values. A visual check is sufficient, see below with age, maximum heart rate achieved and model &lt;code&gt;m3&lt;/code&gt; as example:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# linearity to the log-odds?
dat |&amp;gt;
  dplyr::select(age, max_heartrate) |&amp;gt;
  mutate(log_odds = predict(m3)) |&amp;gt;
  pivot_longer(-log_odds) |&amp;gt;
  ggplot(aes(log_odds, value)) +
  geom_point() +
  geom_smooth(method = &amp;quot;lm&amp;quot;) +
  facet_wrap(~name)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/index_files/figure-html/unnamed-chunk-51-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;ol start=&#34;4&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;in practice, it is recommended to have at least 10 times as many events as parameters in the model, and&lt;/li&gt;
&lt;li&gt;the variance inflation factors (VIF) is a well known measure of multicollinearity. It should be below 10 or 5, depending on the field of research. VIF can be computed with the &lt;code&gt;vif()&lt;/code&gt; function, available in the &lt;code&gt;{car}&lt;/code&gt; package:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load package
library(car)

# compute VIF for model m3
vif(m3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##                   GVIF Df GVIF^(1/(2*Df))
## age           1.205246  1        1.097837
## sex           1.155071  1        1.074742
## chest_pain    1.113010  3        1.018005
## max_heartrate 1.143125  1        1.069170&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;In this relatively long and detailed post, we covered several important points about binary logistic regression. First, when to use such models and what is the difference with linear models, how to implement it in R, and how to interpret and report results. We ended by discussing about model selection, how to judge the quality of fit of a logistic regression, and its underlying assumptions.&lt;/p&gt;
&lt;p&gt;I now hope that (univariable and multivariable) binary logistic regressions in R no longer hold any secrets for you.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;Thanks to Claire from DellaData.fr for introducing me to this package.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Pearson, Spearman and Kendall correlation coefficients by hand</title>
      <link>https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/</link>
      <pubDate>Tue, 05 Sep 2023 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/</guid>
      <description>
&lt;script src=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/htmlwidgets/htmlwidgets.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/datatables-css/datatables-crosstalk.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/datatables-binding/datatables.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/jquery/jquery-3.6.0.min.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/dt-core/css/jquery.dataTables.min.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;link href=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/dt-core/css/jquery.dataTables.extra.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/dt-core/js/jquery.dataTables.min.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/crosstalk/css/crosstalk.min.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/crosstalk/js/crosstalk.min.js&#34;&gt;&lt;/script&gt;

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#data&#34; id=&#34;toc-data&#34;&gt;Data&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#with-ties&#34; id=&#34;toc-with-ties&#34;&gt;With ties&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#without-ties&#34; id=&#34;toc-without-ties&#34;&gt;Without ties&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#correlation-coefficients-by-hand&#34; id=&#34;toc-correlation-coefficients-by-hand&#34;&gt;Correlation coefficients by hand&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#pearson&#34; id=&#34;toc-pearson&#34;&gt;Pearson&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#with-and-without-ties&#34; id=&#34;toc-with-and-without-ties&#34;&gt;With and without ties&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#spearman&#34; id=&#34;toc-spearman&#34;&gt;Spearman&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#with-ties-1&#34; id=&#34;toc-with-ties-1&#34;&gt;With ties&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#without-ties-1&#34; id=&#34;toc-without-ties-1&#34;&gt;Without ties&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#kendall&#34; id=&#34;toc-kendall&#34;&gt;Kendall&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#without-ties-2&#34; id=&#34;toc-without-ties-2&#34;&gt;Without ties&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#with-ties-2&#34; id=&#34;toc-with-ties-2&#34;&gt;With ties&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#verification-in-r&#34; id=&#34;toc-verification-in-r&#34;&gt;Verification in R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;images/pearson-spearman-kendall-correlation-by-hand.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;In statistics, a correlation is used to evaluate the relationship between two variables.&lt;/p&gt;
&lt;p&gt;In a previous post, we showed how to &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;compute a correlation and perform a correlation test in R&lt;/a&gt;. In this post, we illustrate how to compute the Pearson, Spearman and Kendall correlation coefficients by hand and under two different scenarios (i.e., with and without ties).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;data&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Data&lt;/h1&gt;
&lt;p&gt;To illustrate the methods with and without ties, we consider two different datasets, one with ties and another without ties.&lt;/p&gt;
&lt;div id=&#34;with-ties&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;With ties&lt;/h2&gt;
&lt;p&gt;For the illustrations of the scenarios with ties, suppose we have the following sample of size 5:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-1&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-1&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[-1,3,5,5,2],[-3,1,0,2,-1]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/figure-html/unnamed-chunk-1-2.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;As we can see, there are some ties since there are two identical observations in the variable &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;without-ties&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Without ties&lt;/h2&gt;
&lt;p&gt;For the scenarios which require no ties, we will consider the following sample of size 3:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-2&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-2&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[3,5,2],[5,1,-1]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/figure-html/unnamed-chunk-2-2.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;correlation-coefficients-by-hand&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Correlation coefficients by hand&lt;/h1&gt;
&lt;p&gt;The three most common correlation methods are:&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Pearson, used for two &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#continuous&#34;&gt;quantitative continuous&lt;/a&gt; variables which have a linear relationship&lt;/li&gt;
&lt;li&gt;Spearman, used for two quantitative variables if the link is partially linear, or for one &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#ordinal&#34;&gt;qualitative ordinal&lt;/a&gt; variable and one quantitative variable&lt;/li&gt;
&lt;li&gt;Kendall, often used for two qualitative ordinal variables&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Each method is presented in the next sections.&lt;/p&gt;
&lt;p&gt;Note that the aim of this post is to illustrate how to compute the three correlation coefficients by hand and under two different scenarios; we are not interested in verifying the underlying assumptions.&lt;/p&gt;
&lt;div id=&#34;pearson&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Pearson&lt;/h2&gt;
&lt;p&gt;Luckily, the procedure for computing the Pearson correlation coefficient is the same whether there are ties or not so we do not distinguish the two scenarios.&lt;/p&gt;
&lt;div id=&#34;with-and-without-ties&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;With and without ties&lt;/h3&gt;
&lt;p&gt;The Pearson correlation coefficient, denoted &lt;span class=&#34;math inline&#34;&gt;\(r\)&lt;/span&gt; in the case of a sample, can be computed as follows&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
r = \frac{\sum^n_{i = 1} x_i y_i - n \bar{x} \bar{y}}{(n - 1) s_x s_y}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is the sample size&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(x_i\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(y_i\)&lt;/span&gt; are the observations&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\bar{x}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\bar{y}\)&lt;/span&gt; are the sample &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#mean&#34;&gt;means&lt;/a&gt; of &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(s_x\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(s_y\)&lt;/span&gt; are the sample &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#standard-deviation&#34;&gt;standard deviations&lt;/a&gt; of &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We show how to compute it step by step.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 1.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;As you can see, before computing the correlation coefficient we first need to compute the mean and the standard deviation for each of the two variables.&lt;/p&gt;
&lt;p&gt;The mean of &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt; is computed as follows:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\bar{x} = \frac{1}{n}\sum^n_{i = 1} x_i\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The standard deviation of &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt; is computed as follows:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[s_x = \sqrt{\frac{1}{n - 1} \sum^n_{i = 1}(x_i - \bar{x})^2}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The formulas can be used analogously for the variable &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;We start by computing the means of the two variables:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\bar{x} = \frac{-1 + 3 + 5 + 5 + 2}{5} = 2.8\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\bar{y} = \frac{-3 + 1 + 0 + 2 - 1}{5} = -0.2\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Step 2.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We now need to compute the standard deviation of each variable. To ease the computations, it is best to use a table, starting with the observations:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-3&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-3&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[-1,3,5,5,2],[-3,1,0,2,-1]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;To compute the standard deviations, we need the sum of the squared differences between each observation and its mean, that is, &lt;span class=&#34;math inline&#34;&gt;\(\sum^n_{i = 1}(x_i - \bar{x})^2\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\sum^n_{i = 1}(y_i - \bar{y})^2\)&lt;/span&gt;. We start by creating two new columns in the table, denoted &lt;code&gt;x-xbar&lt;/code&gt; and &lt;code&gt;y-ybar&lt;/code&gt;, corresponding to &lt;span class=&#34;math inline&#34;&gt;\((x_i - \bar{x})\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\((y_i - \bar{y})\)&lt;/span&gt;:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-4&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-4&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[-1,3,5,5,2],[-3,1,0,2,-1],[-3.8,0.2,2.2,2.2,-0.8],[-2.8,1.2,0.2,2.2,-0.8]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n      &lt;th&gt;x-xbar&lt;\/th&gt;\n      &lt;th&gt;y-ybar&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1,2,3]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;We take the square of these two new columns to have &lt;span class=&#34;math inline&#34;&gt;\((x_i - \bar{x})^2\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\((y_i - \bar{y})^2\)&lt;/span&gt;, denoted &lt;code&gt;(x-xbar)^2&lt;/code&gt; and &lt;code&gt;(y-ybar)^2&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-5&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-5&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[-1,3,5,5,2],[-3,1,0,2,-1],[-3.8,0.2,2.2,2.2,-0.8],[-2.8,1.2,0.2,2.2,-0.8],[14.44,0.04,4.84,4.84,0.64],[7.84,1.44,0.04,4.84,0.64]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n      &lt;th&gt;x-xbar&lt;\/th&gt;\n      &lt;th&gt;y-ybar&lt;\/th&gt;\n      &lt;th&gt;(x-xbar)^2&lt;\/th&gt;\n      &lt;th&gt;(y-ybar)^2&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1,2,3,4,5]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;We then sum these two columns, which gives:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;for &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\sum^n_{i = 1}(x_i - \bar{x})^2 =\)&lt;/span&gt; 24.8&lt;/li&gt;
&lt;li&gt;for &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\sum^n_{i = 1}(y_i - \bar{y})^2 =\)&lt;/span&gt; 14.8&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The standard deviations are thus:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(s_x = \sqrt{\frac{24.8}{5-1}} = 2.49\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(s_y = \sqrt{\frac{14.8}{5-1}} = 1.92\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Step 3.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We now need &lt;span class=&#34;math inline&#34;&gt;\(\sum^n_{i = 1} x_i y_i\)&lt;/span&gt;, so we add a new column in the table, corresponding to &lt;span class=&#34;math inline&#34;&gt;\(x_iy_i\)&lt;/span&gt; and denoted &lt;code&gt;x*y&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-6&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-6&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[-1,3,5,5,2],[-3,1,0,2,-1],[-3.8,0.2,2.2,2.2,-0.8],[-2.8,1.2,0.2,2.2,-0.8],[14.44,0.04,4.84,4.84,0.64],[7.84,1.44,0.04,4.84,0.64],[3,3,0,10,-2]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n      &lt;th&gt;x-xbar&lt;\/th&gt;\n      &lt;th&gt;y-ybar&lt;\/th&gt;\n      &lt;th&gt;(x-xbar)^2&lt;\/th&gt;\n      &lt;th&gt;(y-ybar)^2&lt;\/th&gt;\n      &lt;th&gt;x*y&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1,2,3,4,5,6]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 4.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We take the sum of that last column, which gives &lt;span class=&#34;math inline&#34;&gt;\(\sum^n_{i = 1} x_i y_i =\)&lt;/span&gt; 14.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 5.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Finally, the Pearson correlation coefficient can be computed by plugging values found above in the initial formula:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
\begin{split}
r &amp;amp;= \frac{\sum^n_{i = 1} x_i y_i - n \bar{x} \bar{y}}{(n - 1) s_x s_y} \\
&amp;amp;= \frac{14 - (5\times2.8\times-0.2)}{(5-1) \times 2.49\times1.92} \\
&amp;amp;= 0.88
\end{split}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Note that there are other formulas to compute the Pearson correlation coefficient. For instance,&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
\begin{split}
r &amp;amp;= \frac{1}{n - 1} \sum^n_{i = 1} \left(\frac{x_i - \bar{x}}{s_x}\right)\left(\frac{y_i - \bar{x}}{s_y}\right) \\
&amp;amp;= \frac{\sum^n_{i = 1}(x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum^n_{i = 1}(x_i - \bar{x})^2} \sqrt{\sum^n_{i = 1}(y_i - \bar{y})^2}}
\end{split}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;All formulas will of course give the exact same results.&lt;/p&gt;
&lt;p&gt;For your information, squaring the Pearson correlation coefficient &lt;span class=&#34;math inline&#34;&gt;\(r\)&lt;/span&gt; gives the coefficient of determination &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; in the context of a simple &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;linear regression&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;spearman&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Spearman&lt;/h2&gt;
&lt;p&gt;We now present the Spearman correlation coefficient, also referred as Spearman’s rank correlation coefficient. This coefficient is actually the same than Pearson coefficient, except that the computations are based on the &lt;em&gt;ranked values&lt;/em&gt; rather than on the raw observations.&lt;/p&gt;
&lt;p&gt;Again, we present how to compute it by hand step by step, but this time we distinguish two scenarios:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;if there are ties&lt;/li&gt;
&lt;li&gt;if there are no ties&lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&#34;with-ties-1&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;With ties&lt;/h3&gt;
&lt;p&gt;The Spearman correlation coefficient (with ties), denoted &lt;span class=&#34;math inline&#34;&gt;\(r_s\)&lt;/span&gt;, is defined as follows&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
r_s = \frac{\sum^n_{i = 1} Rx_i Ry_i - n \overline{Rx} \overline{Ry}}{(n - 1) s_{Rx} s_{Ry}}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is the sample size&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(Rx_i\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(Ry_i\)&lt;/span&gt; are the ranks for the two variables&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\overline{Rx}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\overline{Ry}\)&lt;/span&gt; are the sample means of the ranks for the two variables&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(s_{Rx}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(s_{Ry}\)&lt;/span&gt; are the sample standard deviations of the ranks for the two variables&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here is how to compute it by hand.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 1.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;As mentioned before, the Spearman coefficient is based on the ranks. So we first need to add the ranks of the observations (from lowest to highest), separately for each of the two variables.&lt;/p&gt;
&lt;p&gt;For &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt;, we see that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;-3 is the smallest value, so we assign it the rank 1&lt;/li&gt;
&lt;li&gt;-1 is the second smallest value, so we assign it the rank 2&lt;/li&gt;
&lt;li&gt;then comes 0, so we assign it the rank 3&lt;/li&gt;
&lt;li&gt;then comes 1, so we assign it the rank 4&lt;/li&gt;
&lt;li&gt;finally, 2 is the largest value, so we assign it the rank 5&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The same goes for &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt;, except that here we have two observations with the value 5 (so there will be ties in the ranks). In this case, we take the mean rank:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;-1 is the smallest value, so we assign it the rank 1&lt;/li&gt;
&lt;li&gt;2 is the second smallest value, so we assign it the rank 2&lt;/li&gt;
&lt;li&gt;then comes 3, so we assign it the rank 3&lt;/li&gt;
&lt;li&gt;finally, the two largest values belongs to rank 4 and 5, so we assign both of them the rank 4.5&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We include the ranks in the table, denoted &lt;code&gt;Rx&lt;/code&gt; and &lt;code&gt;Ry&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-7&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-7&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[-1,3,5,5,2],[-3,1,0,2,-1],[1,3,4.5,4.5,2],[1,4,3,5,2]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1,2,3]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 2.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;From there, it is similar than the Pearson coefficient except that we work on the ranks and not on the initial observations anymore. To avoid any confusion in the remaining steps, we remove the initial observations from the table and we keep only the ranks:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-8&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-8&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[1,3,4.5,4.5,2],[1,4,3,5,2]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;We start with the means of the ranks:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\overline{Rx} = \frac{1+3+4.5+4.5+2}{5} = 3\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\overline{Ry} = \frac{1+4+3+5+2}{5} = 3\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For the standard deviations, we use the table as we did for the Pearson coefficient:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-9&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-9&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[1,3,4.5,4.5,2],[1,4,3,5,2],[-2,0,1.5,1.5,-1],[-2,1,0,2,-1],[4,0,2.25,2.25,1],[4,1,0,4,1]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n      &lt;th&gt;Rx-Rxbar&lt;\/th&gt;\n      &lt;th&gt;Ry-Rybar&lt;\/th&gt;\n      &lt;th&gt;(Rx-Rxbar)^2&lt;\/th&gt;\n      &lt;th&gt;(Ry-Rybar)^2&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1,2,3,4,5]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;We sum the last two columns, which gives:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;for &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\sum^n_{i = 1}(Rx_i - \overline{Rx})^2 =\)&lt;/span&gt; 9.5&lt;/li&gt;
&lt;li&gt;for &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\sum^n_{i = 1}(Ry_i - \overline{Ry})^2 =\)&lt;/span&gt; 10&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The standard deviations are thus:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(s_{Rx} = \sqrt{\frac{9.5}{5-1}} = 1.54\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(s_{Ry} = \sqrt{\frac{10}{5-1}} = 1.58\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Step 3.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We now need &lt;span class=&#34;math inline&#34;&gt;\(\sum^n_{i = 1} Rx_i Ry_i\)&lt;/span&gt;, so we add a new column in the table, corresponding to &lt;span class=&#34;math inline&#34;&gt;\(Rx_iRy_i\)&lt;/span&gt; and denoted &lt;code&gt;Rx*Ry&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-10&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-10&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[1,3,4.5,4.5,2],[1,4,3,5,2],[-2,0,1.5,1.5,-1],[-2,1,0,2,-1],[4,0,2.25,2.25,1],[4,1,0,4,1],[1,12,13.5,22.5,4]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n      &lt;th&gt;Rx-Rxbar&lt;\/th&gt;\n      &lt;th&gt;Ry-Rybar&lt;\/th&gt;\n      &lt;th&gt;(Rx-Rxbar)^2&lt;\/th&gt;\n      &lt;th&gt;(Ry-Rybar)^2&lt;\/th&gt;\n      &lt;th&gt;Rx*Ry&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1,2,3,4,5,6]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 4.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We take the sum of that last column, which gives &lt;span class=&#34;math inline&#34;&gt;\(\sum^n_{i = 1} Rx_i Ry_i =\)&lt;/span&gt; 53.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 5.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Finally, the Spearman correlation coefficient can be computed by plugging all values in the initial formula:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
\begin{split}
r_s &amp;amp;= \frac{\sum^n_{i = 1} Rx_i Ry_i - n \overline{Rx} \overline{Ry}}{(n - 1) s_{Rx} s_{Ry}} \\
&amp;amp;= \frac{53 - (5\times3\times3)}{(5-1) \times 1.54\times1.58} \\
&amp;amp;= 0.82
\end{split}
\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;without-ties-1&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Without ties&lt;/h3&gt;
&lt;p&gt;When all initial values are different within each variable, meaning that all ranks are distinct integers, there are no ties. In that specific case, the Spearman coefficient can be computed with the following shortened formula:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
r_s = 1 - \frac{6 \sum^n_{i = 1}(Rx_i - Ry_i)^2}{n (n^2 - 1)}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For example, suppose the sample without ties introduced at the beginning of the post:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-11&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-11&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[3,5,2],[5,1,-1]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 1.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;All observations within each variable are different, so all ranks are distinct integers and there are no ties:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-12&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-12&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[3,5,2],[5,1,-1],[2,3,1],[3,2,1]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1,2,3]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 2.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We only need to compute the difference between the two ranks of each row, denoted &lt;code&gt;Rx-Ry&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-13&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-13&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[3,5,2],[5,1,-1],[2,3,1],[3,2,1],[-1,1,0]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n      &lt;th&gt;Rx-Ry&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1,2,3,4]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Take the square of these differences, denoted &lt;code&gt;(Rx-Ry)^2&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-14&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-14&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[3,5,2],[5,1,-1],[2,3,1],[3,2,1],[-1,1,0],[1,1,0]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n      &lt;th&gt;Rx-Ry&lt;\/th&gt;\n      &lt;th&gt;(Rx-Ry)^2&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1,2,3,4,5]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;And then take the sum of that last column, which gives &lt;span class=&#34;math inline&#34;&gt;\(\sum^n_{i = 1}(Rx_i - Ry_i)^2 =\)&lt;/span&gt; 2.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 3.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Finally, we can fill in the initial formula to find the Spearman coefficient:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
\begin{split}
r_s &amp;amp;= 1 - \frac{6 \sum^n_{i = 1}(Rx_i - Ry_i)^2}{n (n^2 - 1)} \\
&amp;amp;= 1 - \frac{6 \times2}{3 (3^2 - 1)} \\
&amp;amp;= 1 - \frac{12}{24} \\
&amp;amp;= 0.5
\end{split}
\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;kendall&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Kendall&lt;/h2&gt;
&lt;p&gt;Kendall coefficient correlation, also known as Kendall’s &lt;span class=&#34;math inline&#34;&gt;\(\tau\)&lt;/span&gt; coefficient, is similar than Spearman coefficient, except that it is often preferred for small samples and when many rank ties.&lt;/p&gt;
&lt;p&gt;Here also we distinguish between two scenarios:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;if there are no ties&lt;/li&gt;
&lt;li&gt;if there are ties&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Unlike Spearman coefficient, we first illustrate the scenario when there are no ties, and then when there are ties.&lt;/p&gt;
&lt;div id=&#34;without-ties-2&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Without ties&lt;/h3&gt;
&lt;p&gt;When there are no ties, the Kendall coefficient, denoted &lt;span class=&#34;math inline&#34;&gt;\(\tau_a\)&lt;/span&gt;, is defined as follows&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
\tau_a = \frac{C - D}{C + D}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(C\)&lt;/span&gt; is the number of concordant pairs&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(D\)&lt;/span&gt; is the number of discordant pairs&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This coefficient, also referred as Kendall tau-a, does not make any adjustment for ties.&lt;/p&gt;
&lt;p&gt;Let’s see what are concordant and discordant pairs using the data without ties (the same data than for Spearman correlation without ties):&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-15&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-15&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[3,5,2],[5,1,-1]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 1.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We start by computing the ranks for each variable (&lt;code&gt;Rx&lt;/code&gt; and &lt;code&gt;Ry&lt;/code&gt;), as we did for the Spearman coefficient:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-16&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-16&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[3,5,2],[5,1,-1],[2,3,1],[3,2,1]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1,2,3]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 2.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We then arbitrarily choose a reference variable among the two, &lt;code&gt;Rx&lt;/code&gt; or &lt;code&gt;Ry&lt;/code&gt;. Suppose we take &lt;code&gt;Rx&lt;/code&gt; as the reference variable here.&lt;/p&gt;
&lt;p&gt;We sort the dataset by this reference variable:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-17&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-17&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[2,3,5],[-1,5,1],[1,2,3],[1,3,2]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1,2,3]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;From now, we only look at the ranks of the second variable (the one which is &lt;em&gt;not&lt;/em&gt; the reference level, here &lt;code&gt;Ry&lt;/code&gt;), so to avoid any confusion in the remaining steps we keep only the &lt;code&gt;Ry&lt;/code&gt; column:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-18&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-18&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[1,3,2]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:0}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 3.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We now take each row of &lt;code&gt;Ry&lt;/code&gt; one by one and check whether the rows below it in the table are smaller or larger.&lt;/p&gt;
&lt;p&gt;In our table, the first row of &lt;code&gt;Ry&lt;/code&gt; is 1. We see that the value just below it is 3, which is larger than 1. Since 3 is larger than 1, this is called a concordant pair. We write it in the table:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-19&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-19&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[1,3,2],[null,&#34;C&#34;,null]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n      &lt;th&gt;1&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:0}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The next row, 2, is also larger than 1, so it is also a concordant pair. We also write it in the table:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-20&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-20&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[1,3,2],[null,&#34;C&#34;,&#34;C&#34;]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n      &lt;th&gt;1&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:0}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;We start again with the second row of &lt;code&gt;Ry&lt;/code&gt;, which is 3. Again, we look at the row below it and check whether it is larger or smaller. Here, the row below it is 2, which is smaller than 3, so we have a discordant pair. We add this information into the table:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-21&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-21&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[1,3,2],[null,&#34;C&#34;,&#34;C&#34;],[null,null,&#34;D&#34;]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n      &lt;th&gt;1&lt;\/th&gt;\n      &lt;th&gt;3&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:0}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 4.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We now compute the total number of concordant and discordant pairs. There are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;2 concordant pairs so &lt;span class=&#34;math inline&#34;&gt;\(C = 2\)&lt;/span&gt;, and&lt;/li&gt;
&lt;li&gt;1 discordant pair so &lt;span class=&#34;math inline&#34;&gt;\(D = 1\)&lt;/span&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Step 5.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Finally, we plug the values we have just found in the initial formula:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
\begin{split}
\tau_a &amp;amp;= \frac{C - D}{C + D}\\
&amp;amp;= \frac{2 - 1}{2 + 1}\\
&amp;amp;= \frac{1}{3}\\
&amp;amp;= 0.33
\end{split}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Alternatively, we can also use the following formulas&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
\begin{split}
\tau_a &amp;amp;= 1 - \frac{4D}{n(n - 1)}\\
&amp;amp;= \frac{4C}{n(n - 1)} - 1
\end{split}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is still the sample size, and which both give the exact same results.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;with-ties-2&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;With ties&lt;/h3&gt;
&lt;p&gt;I must admit that the process with ties is slightly more complex than without ties.&lt;/p&gt;
&lt;p&gt;The Kendall tau-b coefficient, which makes adjustments for ties, is defined as follows&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
\tau_b = \frac{C - D}{\sqrt{(C^2_n - n_x)(C^2_n - n_y)}}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(C\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(D\)&lt;/span&gt; are still the number of concordant and discordant pairs, respectively&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(C^2_n\)&lt;/span&gt; is the total number of possible pairs&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(n_x\)&lt;/span&gt; is the number of possible pairs &lt;em&gt;with a tie&lt;/em&gt; among the &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt; values&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(n_y\)&lt;/span&gt; is the number of possible pairs &lt;em&gt;with a tie&lt;/em&gt; among the &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt; values&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that here, the letter &lt;span class=&#34;math inline&#34;&gt;\(C\)&lt;/span&gt; in &lt;span class=&#34;math inline&#34;&gt;\(C^2_n\)&lt;/span&gt; denotes “combination” and not “concordant”.&lt;/p&gt;
&lt;p&gt;Let’s illustrate that scenario and the formula with the dataset used for the Pearson correlation and the Spearman correlation with ties, that is:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-22&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-22&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[-1,3,5,5,2],[-3,1,0,2,-1]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 1.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Similarly to with no ties, the process with ties is based on the ranks so we start by adding the ranks for each variable, denoted as usual as &lt;code&gt;Rx&lt;/code&gt; and &lt;code&gt;Ry&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-23&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-23&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[-1,3,5,5,2],[-3,1,0,2,-1],[1,3,4.5,4.5,2],[1,4,3,5,2]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;x&lt;\/th&gt;\n      &lt;th&gt;y&lt;\/th&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1,2,3]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 2.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;One of the two variables (&lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt; or &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt;) must be selected as the reference variable. This time, we do not choose it arbitrarily, but we choose the one which does not have any ties. In our case, variable &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt; has ties, while variable &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt; does not have any ties. So &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt; will be our reference variable.&lt;/p&gt;
&lt;p&gt;We then:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;order the dataset by the reference variable, here &lt;code&gt;Ry&lt;/code&gt;, and&lt;/li&gt;
&lt;li&gt;we keep only the necessary columns to avoid any confusion in the remaining steps:&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-24&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-24&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[1,2,3,4,5],[1,2,4.5,3,4.5]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 3.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We check whether it is a concordant or discordant pair the same way we did without ties, but this time we do not count ties.&lt;/p&gt;
&lt;p&gt;The first row in column &lt;code&gt;Rx&lt;/code&gt; is 1. We compare all rows below it in the table with that value. All rows below 1 in the table are larger, so we write that they are concordant pairs:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-25&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-25&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[1,2,3,4,5],[1,2,4.5,3,4.5],[null,&#34;C&#34;,&#34;C&#34;,&#34;C&#34;,&#34;C&#34;]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;1&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;We repeat the same process for each row.&lt;/p&gt;
&lt;p&gt;For instance, for the second row of the column &lt;code&gt;Rx&lt;/code&gt;, we have the value 2. Again, all rows below in the table are larger so we write that they are concordant pairs:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-26&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-26&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[1,2,3,4,5],[1,2,4.5,3,4.5],[null,&#34;C&#34;,&#34;C&#34;,&#34;C&#34;,&#34;C&#34;],[null,null,&#34;C&#34;,&#34;C&#34;,&#34;C&#34;]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;1&lt;\/th&gt;\n      &lt;th&gt;2&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;For the third row of the column &lt;code&gt;Rx&lt;/code&gt;, we have the value 4.5. The row just below in the table (= 3) is smaller than 4, so we write D for discordant pair:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-27&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-27&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[1,2,3,4,5],[1,2,4.5,3,4.5],[null,&#34;C&#34;,&#34;C&#34;,&#34;C&#34;,&#34;C&#34;],[null,null,&#34;C&#34;,&#34;C&#34;,&#34;C&#34;],[null,null,null,&#34;D&#34;,null]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;1&lt;\/th&gt;\n      &lt;th&gt;2&lt;\/th&gt;\n      &lt;th&gt;4.5&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Now, as you can see, the last row is also 4.5. Therefore, since it is equal to the value we are comparing to, it is neither a concordant nor a discordant pair, so we write “T” in the table for “ties”:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-28&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-28&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[1,2,3,4,5],[1,2,4.5,3,4.5],[null,&#34;C&#34;,&#34;C&#34;,&#34;C&#34;,&#34;C&#34;],[null,null,&#34;C&#34;,&#34;C&#34;,&#34;C&#34;],[null,null,null,&#34;D&#34;,&#34;T&#34;]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;1&lt;\/th&gt;\n      &lt;th&gt;2&lt;\/th&gt;\n      &lt;th&gt;4.5&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Last, the fourth row in the column &lt;code&gt;Rx&lt;/code&gt; is 3, which we compare to 4.5 to see that 4.5 is larger so it is a concordant pair:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-29&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-29&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[1,2,3,4,5],[1,2,4.5,3,4.5],[null,&#34;C&#34;,&#34;C&#34;,&#34;C&#34;,&#34;C&#34;],[null,null,&#34;C&#34;,&#34;C&#34;,&#34;C&#34;],[null,null,null,&#34;D&#34;,&#34;T&#34;],[null,null,null,null,&#34;C&#34;]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n      &lt;th&gt;1&lt;\/th&gt;\n      &lt;th&gt;2&lt;\/th&gt;\n      &lt;th&gt;4.5&lt;\/th&gt;\n      &lt;th&gt;3&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 4.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We then sum the number of concordant and discordant pairs:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(C = 8\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(D = 1\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Step 5.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We now have all the information required to compute the numerator of &lt;span class=&#34;math inline&#34;&gt;\(\tau_b\)&lt;/span&gt;, but we still need to find &lt;span class=&#34;math inline&#34;&gt;\(C^2_n\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(n_x\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(n_y\)&lt;/span&gt; to compute the denominator.&lt;/p&gt;
&lt;p&gt;As mentioned above, &lt;span class=&#34;math inline&#34;&gt;\(C^2_n\)&lt;/span&gt; is the total number of possible pairs, thus corresponding to the number of combinations of two values. This number of pairs can be found with the formula of the &lt;a href=&#34;https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/#combination&#34;&gt;combination&lt;/a&gt;, that is, &lt;span class=&#34;math inline&#34;&gt;\(C^2_n = \frac{n!}{2!(n - 2)!}\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is the sample size.&lt;/p&gt;
&lt;p&gt;In our case, we have a sample of size 5, so we have:&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
\begin{split}
C^2_n &amp;amp;= \frac{n!}{2!(n - 2)!}\\
&amp;amp;= \frac{5!}{2!(5-2)!}\\
&amp;amp;= 10
\end{split}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Furthermore, &lt;span class=&#34;math inline&#34;&gt;\(n_x\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(n_y\)&lt;/span&gt; are the number of possible pairs &lt;strong&gt;with a tie&lt;/strong&gt; among the &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt; variables, respectively.&lt;/p&gt;
&lt;p&gt;When looking at &lt;code&gt;Ry&lt;/code&gt; and &lt;code&gt;Rx&lt;/code&gt; from the table above:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item-overflow-hidden html-fill-item&#34; id=&#34;htmlwidget-30&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-30&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[1,2,3,4,5],[1,2,4.5,3,4.5]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Ry&lt;\/th&gt;\n      &lt;th&gt;Rx&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1]}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;We see that there are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;2 identical values for the variable &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;0 identical value for the variable &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This means that the number of possible &lt;strong&gt;pairs&lt;/strong&gt; with a tie is equal to:&lt;a href=&#34;#fn4&#34; class=&#34;footnote-ref&#34; id=&#34;fnref4&#34;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 for the variable &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt; (the only possible pair with a tie is the pair {4.5, 4.5})&lt;/li&gt;
&lt;li&gt;0 for the variable &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt; (since all ranks are distinct, there exists no pair with a tie)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Therefore,&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
\begin{split}
n_x &amp;amp;= 1\\
n_y &amp;amp;= 0
\end{split}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;And we now have all the necessary information to compute &lt;span class=&#34;math inline&#34;&gt;\(\tau_b\)&lt;/span&gt;!&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 6.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;By plugging the values found above in the initial formula, we have&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
\begin{split}
\tau_b &amp;amp;= \frac{C - D}{\sqrt{(C^2_n - n_x)(C^2_n - n_y)}}\\
&amp;amp;= \frac{8-1}{\sqrt{(10 - 1)(10 - 0)}}\\
&amp;amp;= \frac{7}{\sqrt{90}}\\
&amp;amp;= 0.74
\end{split}
\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;verification-in-r&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Verification in R&lt;/h1&gt;
&lt;p&gt;For the sake of completeness, we verify our results with the help of R for each coefficient and scenario.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Pearson:&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x &amp;lt;- c(-1, 3, 5, 5, 2)
y &amp;lt;- c(-3, 1, 0, 2, -1)

cor(x, y, method = &amp;quot;pearson&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.8769051&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Spearman with ties:&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;cor(x, y, method = &amp;quot;spearman&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.8207827&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Spearman without ties:&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x2 &amp;lt;- c(3, 5, 2)
y2 &amp;lt;- c(5, 1, -1)

cor(x2, y2, method = &amp;quot;spearman&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.5&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Kendall without ties:&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;cor(x2, y2, method = &amp;quot;kendall&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.3333333&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Kendall with ties:&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;cor(x, y, method = &amp;quot;kendall&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.7378648&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We indeed find the same results by hand than with R (any discrepancies is due to rounding)!&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Remember that a correlation coefficient (no matter whether it is Pearson, Spearman or Kendall) ranges from -1 to 1, with 0 being no correlation and the closer to 1 in absolute terms, the stronger the correlation.&lt;/p&gt;
&lt;p&gt;Broadly speaking, a positive correlation means that high values of one variable are associated with high values of the other variable (and vice versa). A negative correlation means that high values of one variable are associated with low values of the other variable.
&lt;!-- And a correlation close to 0 means that there are no linear relationship between the two variables of interest. --&gt;&lt;/p&gt;
&lt;p&gt;Last but not least, remember that the conclusions drawn from a correlation coefficient computed within a sample cannot be generalized to the population without a proper statistical test, that is, a &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/#correlation-test&#34;&gt;correlation test&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to compute the Pearson, Spearman and Kendall correlation coefficients by hand (with and without ties).&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;For your information, the Pearson correlation coefficient is considered as a parametric procedure, whereas the Spearman and Kendall correlation coefficients are considered as non-parametric procedures.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Here, we suppose that we have a sample and not a population. In the case where the observations you have represent the entire population, the correlation coefficient is denoted &lt;span class=&#34;math inline&#34;&gt;\(\rho\)&lt;/span&gt; and the formula differs slightly. See a recap of the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;difference between a sample and a population&lt;/a&gt; if needed.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;Remember that the factorial of &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt;, denoted &lt;span class=&#34;math inline&#34;&gt;\(n!\)&lt;/span&gt;, is &lt;span class=&#34;math inline&#34;&gt;\(n! = n \times (n - 1) \times \cdots \times 1\)&lt;/span&gt;. So for instance, &lt;span class=&#34;math inline&#34;&gt;\(5! = 5\times4\times3\times2\times1 = 120\)&lt;/span&gt;.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;If you have many identical values and want to count the number of possible pairs thanks to a formula rather than by counting them manually, you can again use the formula of the &lt;a href=&#34;https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/#combination&#34;&gt;combination&lt;/a&gt;, that is, &lt;span class=&#34;math inline&#34;&gt;\(C^2_n = \frac{n!}{x!(n - x)!}\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is the number of identical values in a given group of ties. Bear in mind that the number of combinations must be summed up for all group of ties. In our case, we have only one group of ties with 2 values, so &lt;span class=&#34;math inline&#34;&gt;\(n_x = C^2_2 = \frac{2!}{2!(2 - 2)!} = 1\)&lt;/span&gt;.&lt;a href=&#34;#fnref4&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>How to: one-way ANOVA by hand</title>
      <link>https://statsandr.com/blog/how-to-one-way-anova-by-hand/</link>
      <pubDate>Wed, 30 Aug 2023 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/how-to-one-way-anova-by-hand/</guid>
      <description>
&lt;link href=&#34;https://statsandr.com/blog/how-to-one-way-anova-by-hand/index_files/htmltools-fill/fill.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/blog/how-to-one-way-anova-by-hand/index_files/htmlwidgets/htmlwidgets.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;https://statsandr.com/blog/how-to-one-way-anova-by-hand/index_files/datatables-css/datatables-crosstalk.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/blog/how-to-one-way-anova-by-hand/index_files/datatables-binding/datatables.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;https://statsandr.com/blog/how-to-one-way-anova-by-hand/index_files/jquery/jquery-3.6.0.min.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;https://statsandr.com/blog/how-to-one-way-anova-by-hand/index_files/dt-core/css/jquery.dataTables.min.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;link href=&#34;https://statsandr.com/blog/how-to-one-way-anova-by-hand/index_files/dt-core/css/jquery.dataTables.extra.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/blog/how-to-one-way-anova-by-hand/index_files/dt-core/js/jquery.dataTables.min.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;https://statsandr.com/blog/how-to-one-way-anova-by-hand/index_files/crosstalk/css/crosstalk.min.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/blog/how-to-one-way-anova-by-hand/index_files/crosstalk/js/crosstalk.min.js&#34;&gt;&lt;/script&gt;

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#data-and-hypotheses&#34; id=&#34;toc-data-and-hypotheses&#34;&gt;Data and hypotheses&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#anova-by-hand&#34; id=&#34;toc-anova-by-hand&#34;&gt;ANOVA by hand&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#overall-and-group-means&#34; id=&#34;toc-overall-and-group-means&#34;&gt;Overall and group means&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#ssr-and-sse&#34; id=&#34;toc-ssr-and-sse&#34;&gt;SSR and SSE&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#anova-table&#34; id=&#34;toc-anova-table&#34;&gt;ANOVA table&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion-of-the-test&#34; id=&#34;toc-conclusion-of-the-test&#34;&gt;Conclusion of the test&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;images/how-to-one-way-anova-by-hand.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;An ANOVA is a statistical test used to compare a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#quantitative&#34;&gt;quantitative variable&lt;/a&gt; between groups, to determine if there is a statistically significant difference between several population means. In practice, it is usually used to compare three or more groups. However, in theory, it can also be done with only two groups.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In a previous post, we showed how to perform a &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;one-way ANOVA in R&lt;/a&gt;. In this post, we illustrate how to conduct a one-way ANOVA by hand, via what is usually called an “ANOVA table”.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;data-and-hypotheses&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Data and hypotheses&lt;/h1&gt;
&lt;p&gt;To illustrate the method, suppose we take a &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;sample&lt;/a&gt; of 12 students, divided equally into three classes (A, B and C) and we observe their age. Here is the sample:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-1&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-1&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[24,31,26,23],[24,21,19,24],[15,21,18,18]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;A&lt;\/th&gt;\n      &lt;th&gt;B&lt;\/th&gt;\n      &lt;th&gt;C&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1,2]},{&#34;name&#34;:&#34;A&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;B&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;C&#34;,&#34;targets&#34;:2}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;We are interested in comparing the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;population&lt;/a&gt; means between classes.&lt;/p&gt;
&lt;p&gt;Remember that the null hypothesis of the ANOVA is that all means are equal (i.e., age is not significantly different between classes), whereas the alternative hypothesis is that at least one mean is different from the other two (i.e., age is significantly different in at least one class compared to the other two). Formally, we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\mu_A = \mu_B = \mu_C\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;at least one mean is different&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;anova-by-hand&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;ANOVA by hand&lt;/h1&gt;
&lt;p&gt;As mentioned above, we are going to do an ANOVA table to conclude the test.&lt;/p&gt;
&lt;p&gt;Note that the ANOVA requires some assumptions (i.e., independence, equality of variances and normality). The aim of this post is to illustrate how to do an ANOVA by hand and not how to verify these assumptions, so we suppose they are met without any verification. See how to &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#underlying-assumptions-of-anova&#34;&gt;test these assumptions in R&lt;/a&gt; if you are interested.&lt;/p&gt;
&lt;div id=&#34;overall-and-group-means&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Overall and group means&lt;/h2&gt;
&lt;p&gt;We first need to compute the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#mean&#34;&gt;mean&lt;/a&gt; age by class (referred as the group means):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;class A: &lt;span class=&#34;math inline&#34;&gt;\(\frac{24 + 31 + 26 + 23}{4} = 26\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;class B: &lt;span class=&#34;math inline&#34;&gt;\(\frac{24 + 21 + 19 + 24}{4} = 22\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;class C: &lt;span class=&#34;math inline&#34;&gt;\(\frac{15 + 21 + 18 + 18}{4} = 18\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;and the mean age for the whole sample (referred as the overall mean):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{equation}
\begin{split}
&amp;amp;       \frac{24 + 31 + 26 + 23 + 24 + 21 + 19 }{12}    \\
&amp;amp;\frac{+ 24 + 15 + 21 + 18 + 18}{12} = 22
\end{split}
\end{equation}
\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;ssr-and-sse&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;SSR and SSE&lt;/h2&gt;
&lt;p&gt;We then need to compute the sum of squares regression (SSR), and the sum of squares error (SSE).&lt;/p&gt;
&lt;p&gt;The SSR is computed by taking the square of the difference between the mean group and the overall mean, multiplied by the number of observations in the group:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-2&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-2&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[&#34;4 * ((26 - 22)^2) = 64&#34;],[&#34;4 * ((22 - 22)^2) = 0&#34;],[&#34;4 * ((18 - 22)^2) = 64&#34;]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;A&lt;\/th&gt;\n      &lt;th&gt;B&lt;\/th&gt;\n      &lt;th&gt;C&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;name&#34;:&#34;A&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;B&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;C&#34;,&#34;targets&#34;:2}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;and then taking the sum of all cells:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[64+0+64 = 128 = SSR\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The SSE is computed by taking the square of the difference between each observation and its group mean:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-3&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-3&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[&#34;(24 - 26)^2 = 4&#34;,&#34;(31 - 26)^2 = 25&#34;,&#34;(26 - 26)^2 = 0&#34;,&#34;(23 - 26)^2 = 9&#34;],[&#34;(24 - 22)^2 = 4&#34;,&#34;(21 - 22)^2 = 1&#34;,&#34;(19 - 22)^2 = 9&#34;,&#34;(24 - 22)^2 = 4&#34;],[&#34;(15 - 18)^2 = 9&#34;,&#34;(21 - 18)^2 = 9&#34;,&#34;(18 - 18)^2 = 0&#34;,&#34;(18 - 18)^2 = 0&#34;]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;A&lt;\/th&gt;\n      &lt;th&gt;B&lt;\/th&gt;\n      &lt;th&gt;C&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;name&#34;:&#34;A&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;B&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;C&#34;,&#34;targets&#34;:2}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;and then taking the sum of all cells:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{equation}
\begin{split}
&amp;amp; 4+25+0+9+4+1+9+4    \\
&amp;amp; +9+9+0+0 = 74 = SSE
\end{split}
\end{equation}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For those interested in computing the sum of square total (SST), it is simply the sum of SSR and SSE, that is,&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{equation}
\begin{split}
SST &amp;amp;= SSR + SSE\\
&amp;amp;= 128 + 74 \\
&amp;amp; =202
\end{split}
\end{equation}
\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;anova-table&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;ANOVA table&lt;/h2&gt;
&lt;p&gt;The ANOVA table looks as follows (we leave it empty and we are going to fill it in step by step):&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-4&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-4&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[&#34;Regression&#34;,&#34;Error&#34;],[null,null],[null,null],[null,null],[null,null]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Type&lt;\/th&gt;\n      &lt;th&gt;Sum.of.Sq.&lt;\/th&gt;\n      &lt;th&gt;Df&lt;\/th&gt;\n      &lt;th&gt;Mean.Sq.&lt;\/th&gt;\n      &lt;th&gt;F.value&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;name&#34;:&#34;Type&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;Sum.of.Sq.&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;Df&#34;,&#34;targets&#34;:2},{&#34;name&#34;:&#34;Mean.Sq.&#34;,&#34;targets&#34;:3},{&#34;name&#34;:&#34;F.value&#34;,&#34;targets&#34;:4}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;We start to build the ANOVA table by plugging the SSR and SSE values found above into the table (in the “Sum.of.Sq.” column):&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-5&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-5&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[&#34;Regression&#34;,&#34;Error&#34;],[128,74],[null,null],[null,null],[null,null]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Type&lt;\/th&gt;\n      &lt;th&gt;Sum.of.Sq.&lt;\/th&gt;\n      &lt;th&gt;Df&lt;\/th&gt;\n      &lt;th&gt;Mean.Sq.&lt;\/th&gt;\n      &lt;th&gt;F.value&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;Type&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;Sum.of.Sq.&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;Df&#34;,&#34;targets&#34;:2},{&#34;name&#34;:&#34;Mean.Sq.&#34;,&#34;targets&#34;:3},{&#34;name&#34;:&#34;F.value&#34;,&#34;targets&#34;:4}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The “Df” column corresponds to the degrees of freedom, and is computed as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;for the line regression: number of groups - 1 = 3 - 1 = 2&lt;/li&gt;
&lt;li&gt;for the line error: number of observations - number of groups = 12 - 3 = 9&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;With this information, the ANOVA table becomes:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-6&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-6&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[&#34;Regression&#34;,&#34;Error&#34;],[128,74],[2,9],[null,null],[null,null]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Type&lt;\/th&gt;\n      &lt;th&gt;Sum.of.Sq.&lt;\/th&gt;\n      &lt;th&gt;Df&lt;\/th&gt;\n      &lt;th&gt;Mean.Sq.&lt;\/th&gt;\n      &lt;th&gt;F.value&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[1,2]},{&#34;name&#34;:&#34;Type&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;Sum.of.Sq.&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;Df&#34;,&#34;targets&#34;:2},{&#34;name&#34;:&#34;Mean.Sq.&#34;,&#34;targets&#34;:3},{&#34;name&#34;:&#34;F.value&#34;,&#34;targets&#34;:4}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The “Mean.Sq.” column corresponds to the Mean Square, and is equal to the sum of square divided by the degrees of freedom, so the “Sum.of.Sq.” column divided by the “Df” column:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-7&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-7&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[&#34;Regression&#34;,&#34;Error&#34;],[128,74],[2,9],[64,8.222],[null,null]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Type&lt;\/th&gt;\n      &lt;th&gt;Sum.of.Sq.&lt;\/th&gt;\n      &lt;th&gt;Df&lt;\/th&gt;\n      &lt;th&gt;Mean.Sq.&lt;\/th&gt;\n      &lt;th&gt;F.value&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[1,2,3]},{&#34;name&#34;:&#34;Type&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;Sum.of.Sq.&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;Df&#34;,&#34;targets&#34;:2},{&#34;name&#34;:&#34;Mean.Sq.&#34;,&#34;targets&#34;:3},{&#34;name&#34;:&#34;F.value&#34;,&#34;targets&#34;:4}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Finally, the F-value corresponds to the ratio between the two mean squares, so &lt;span class=&#34;math inline&#34;&gt;\(\frac{64}{8.222} = 7.78\)&lt;/span&gt;:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-8&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-8&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[&#34;Regression&#34;,&#34;Error&#34;],[128,74],[2,9],[64,8.222],[7.78,null]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Type&lt;\/th&gt;\n      &lt;th&gt;Sum.of.Sq.&lt;\/th&gt;\n      &lt;th&gt;Df&lt;\/th&gt;\n      &lt;th&gt;Mean.Sq.&lt;\/th&gt;\n      &lt;th&gt;F.value&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[1,2,3,4]},{&#34;name&#34;:&#34;Type&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;Sum.of.Sq.&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;Df&#34;,&#34;targets&#34;:2},{&#34;name&#34;:&#34;Mean.Sq.&#34;,&#34;targets&#34;:3},{&#34;name&#34;:&#34;F.value&#34;,&#34;targets&#34;:4}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;This F-value gives the test statistic (also referred as &lt;span class=&#34;math inline&#34;&gt;\(F_{obs}\)&lt;/span&gt;), which needs to be compared with the critical value found in the Fisher table to conclude the test.&lt;/p&gt;
&lt;p&gt;We find the critical value in the Fisher table based on the degrees of freedom (those used in the ANOVA table) and based on the significance level. Suppose we take a significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;, the critical value can be found in the Fisher table as follows:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;images/anova-by-hand-fisher-table.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;So we have&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[F_{2; 9; 0.05} = 4.26\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;If you are interested to find this value with R, it can be found with the &lt;code&gt;qf()&lt;/code&gt; function, where 0.95 corresponds to &lt;span class=&#34;math inline&#34;&gt;\(1 - \alpha\)&lt;/span&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;qf(0.95, 2, 9)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 4.256495&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion-of-the-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Conclusion of the test&lt;/h2&gt;
&lt;p&gt;The rejection rule says that, if:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(F_{obs} &amp;gt; F_{2; 9; 0.05} \Rightarrow\)&lt;/span&gt; we reject the null hypothesis&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(F_{obs} \le F_{2; 9; 0.05} \Rightarrow\)&lt;/span&gt; we &lt;em&gt;do not&lt;/em&gt; reject the null hypothesis&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In our case,&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[F_{obs} = 7.78 &amp;gt; F_{2; 9; 0.05} = 4.26\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(\Rightarrow\)&lt;/span&gt; We reject the null hypothesis that all means are equal. In other words, it means that at least one class is different than the other two in terms of age.&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;To verify our results, here is the ANOVA table using R:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;##             Df Sum Sq Mean Sq F value Pr(&amp;gt;F)  
## class        2    128   64.00   7.784 0.0109 *
## Residuals    9     74    8.22                 
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We found the same results by hand, but note that in R, the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value is computed instead of comparing the &lt;span class=&#34;math inline&#34;&gt;\(F_{obs}\)&lt;/span&gt; with the critical value. The &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value can easily be found in R based on the &lt;span class=&#34;math inline&#34;&gt;\(F_{obs}\)&lt;/span&gt; and the degrees of freedom:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;pf(7.78, 2, 9,
  lower.tail = FALSE
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.010916&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to conduct a one-way ANOVA by hand. See this &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;tutorial&lt;/a&gt; if you want to learn how to do it in R.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;In that case, a &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test&lt;/a&gt; is usually preferred over an ANOVA, although both tests will lead to the exact same conclusions.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Remember that an ANOVA cannot tell you which group is different than the other in terms of the quantitative dependent variable, nor whether they are all different or if only one is different. To answer this question, post-hoc tests are required. This is beyond the scope of the present post, but it can easily be done in R (see this &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;tutorial&lt;/a&gt;).&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Two-way ANOVA in R</title>
      <link>https://statsandr.com/blog/two-way-anova-in-r/</link>
      <pubDate>Mon, 19 Jun 2023 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/two-way-anova-in-r/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#data&#34; id=&#34;toc-data&#34;&gt;Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#aim-and-hypotheses-of-a-two-way-anova&#34; id=&#34;toc-aim-and-hypotheses-of-a-two-way-anova&#34;&gt;Aim and hypotheses of a two-way ANOVA&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#assumptions-of-a-two-way-anova&#34; id=&#34;toc-assumptions-of-a-two-way-anova&#34;&gt;Assumptions of a two-way ANOVA&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#variable-type&#34; id=&#34;toc-variable-type&#34;&gt;Variable type&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#independence&#34; id=&#34;toc-independence&#34;&gt;Independence&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#normality&#34; id=&#34;toc-normality&#34;&gt;Normality&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#homogeneity-of-variances&#34; id=&#34;toc-homogeneity-of-variances&#34;&gt;Homogeneity of variances&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#outliers&#34; id=&#34;toc-outliers&#34;&gt;Outliers&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#two-way-anova&#34; id=&#34;toc-two-way-anova&#34;&gt;Two-way ANOVA&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#preliminary-analyses&#34; id=&#34;toc-preliminary-analyses&#34;&gt;Preliminary analyses&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#descriptive-statistics&#34; id=&#34;toc-descriptive-statistics&#34;&gt;Descriptive statistics&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#plots&#34; id=&#34;toc-plots&#34;&gt;Plots&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#two-way-anova-in-r&#34; id=&#34;toc-two-way-anova-in-r&#34;&gt;Two-way ANOVA in R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#pairwise-comparisons&#34; id=&#34;toc-pairwise-comparisons&#34;&gt;Pairwise comparisons&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#visualizations&#34; id=&#34;toc-visualizations&#34;&gt;Visualizations&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;images/two-way-anova-in-r.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;The two-way ANOVA (analysis of variance) is a statistical method that allows to &lt;strong&gt;evaluate the simultaneous effect of two &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;categorical&lt;/a&gt; variables on a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#continuous&#34;&gt;quantitative continuous&lt;/a&gt; variable&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The two-way ANOVA is an extension of the one-way ANOVA since it allows to evaluate the effects on a numerical response of &lt;strong&gt;two&lt;/strong&gt; categorical variables instead of one.&lt;/p&gt;
&lt;p&gt;The advantage of a two-way ANOVA over a one-way ANOVA is that we test the relationship between two variables, while taking into account the effect of a third variable. Moreover, it also allows to include the possible &lt;em&gt;interaction&lt;/em&gt; of the two categorical variables on the response to evaluate whether or not they act &lt;strong&gt;jointly&lt;/strong&gt; on the response variable.&lt;/p&gt;
&lt;p&gt;The advantage of a two-way over a one-way ANOVA is quite similar to the advantage of a &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;multiple linear regression&lt;/a&gt; over a &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;correlation&lt;/a&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The correlation measures the relationship between two quantitative variables. The multiple linear regression also measures the relationship between two variables, but this time taking into account the potential effect of other covariates.&lt;/li&gt;
&lt;li&gt;The one-way ANOVA tests whether a quantitative variable is different between groups. The two-way ANOVA also tests whether a quantitative variable is different between groups, but this time taking into account the effect of another qualitative variable.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Previously, we have discussed about &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;one-way ANOVA in R&lt;/a&gt;. Now, we show when, why and how to perform a &lt;strong&gt;two-way&lt;/strong&gt; ANOVA in R.&lt;/p&gt;
&lt;p&gt;Before going further, I would like to mention and briefly describe some related statistical methods and tests in order to avoid any confusion:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test&lt;/a&gt; is used to evaluate the effect of one categorical variable on a quantitative continuous variable, &lt;strong&gt;when the categorical variable has exactly 2 levels&lt;/strong&gt;:
&lt;ul&gt;
&lt;li&gt;Student’s t-test &lt;em&gt;for independent samples&lt;/em&gt; if the observations are &lt;strong&gt;independent&lt;/strong&gt; (for example: if we compare the age between women and men)&lt;/li&gt;
&lt;li&gt;Student’s t-test &lt;em&gt;for paired samples&lt;/em&gt; if the observations are &lt;strong&gt;dependent&lt;/strong&gt;, that is, when they come in pairs (it is the case when the same subjects are measured twice, at two different points in time, before and after a treatment for example)&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;To evaluate the effect of one categorical variable on a quantitative variable, &lt;strong&gt;when the categorical variable has 3 or more levels&lt;/strong&gt;:&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;&lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;one-way ANOVA&lt;/a&gt;&lt;/em&gt; (often simply referred as ANOVA) if the groups are &lt;strong&gt;independent&lt;/strong&gt; (for example a group of patients who received treatment A, another group of patients who received treatment B, and the last group of patients who received no treatment or a placebo)&lt;/li&gt;
&lt;li&gt;&lt;em&gt;repeated measures ANOVA&lt;/em&gt; if the groups are &lt;strong&gt;dependent&lt;/strong&gt; (when the same subjects are measured three times, at three different points in time, before, during and after a treatment for example)&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;A two-way ANOVA is used to evaluate the effects of 2 categorical variables (and their potential interaction) on a quantitative continuous variable. This is the topic of the post.&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;Linear regression&lt;/a&gt; is used to evaluate the relationship between a quantitative continuous dependent variable and one or several independent variables:
&lt;ul&gt;
&lt;li&gt;simple linear regression if there is only one independent variable (which can be quantitative or qualitative)&lt;/li&gt;
&lt;li&gt;multiple linear regression if there is at least two independent variables (which can be quantitative, qualitative, or a mix of both)&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;An ANCOVA (analysis of covariance) is used to evaluate the effect of a categorical variable on a quantitative variable, while controlling for the effect of another quantitative variable (known as covariate). ANCOVA is actually a special case of multiple linear regression with a mix of one qualitative and one quantitative independent variable.&lt;/li&gt;
&lt;li&gt;A mixed ANOVA is used to test differences between two or more groups whilst subjecting participants to repeated measures: one factor (a fixed effects factor) is a between-subjects variable (for example, treatment A and B, with patients receiving only one of the two treatments) and the other (a random effects factor) is a within-subjects variable (for example, measurements are made on day 1, day 2 and day 3 on all subjects).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In this post, we start by explaining when and why a two-way ANOVA is useful, we then do some preliminary descriptive analyses and present how to conduct a two-way ANOVA in R. Finally, we show how to interpret and visualize the results. We also briefly mention and illustrate how to verify the underlying assumptions.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;data&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Data&lt;/h1&gt;
&lt;p&gt;To illustrate how to perform a two-way ANOVA in R, we use the &lt;code&gt;penguins&lt;/code&gt; dataset, available from the &lt;code&gt;{palmerpenguins}&lt;/code&gt; package.&lt;/p&gt;
&lt;p&gt;We do not need to &lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/&#34;&gt;import the dataset&lt;/a&gt;, but we need to &lt;a href=&#34;https://statsandr.com/blog/an-efficient-way-to-install-and-load-r-packages/&#34;&gt;load the package&lt;/a&gt; first and then call the dataset:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# install.packages(&amp;quot;palmerpenguins&amp;quot;)
library(palmerpenguins)

dat &amp;lt;- penguins # rename dataset
str(dat) # structure of dataset&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## tibble [344 × 8] (S3: tbl_df/tbl/data.frame)
##  $ species          : Factor w/ 3 levels &amp;quot;Adelie&amp;quot;,&amp;quot;Chinstrap&amp;quot;,..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ island           : Factor w/ 3 levels &amp;quot;Biscoe&amp;quot;,&amp;quot;Dream&amp;quot;,..: 3 3 3 3 3 3 3 3 3 3 ...
##  $ bill_length_mm   : num [1:344] 39.1 39.5 40.3 NA 36.7 39.3 38.9 39.2 34.1 42 ...
##  $ bill_depth_mm    : num [1:344] 18.7 17.4 18 NA 19.3 20.6 17.8 19.6 18.1 20.2 ...
##  $ flipper_length_mm: int [1:344] 181 186 195 NA 193 190 181 195 193 190 ...
##  $ body_mass_g      : int [1:344] 3750 3800 3250 NA 3450 3650 3625 4675 3475 4250 ...
##  $ sex              : Factor w/ 2 levels &amp;quot;female&amp;quot;,&amp;quot;male&amp;quot;: 2 1 1 NA 1 2 1 2 NA NA ...
##  $ year             : int [1:344] 2007 2007 2007 2007 2007 2007 2007 2007 2007 2007 ...&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The dataset contains 8 variables for 344 penguins, summarized below:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       species          island    bill_length_mm  bill_depth_mm  
##  Adelie   :152   Biscoe   :168   Min.   :32.10   Min.   :13.10  
##  Chinstrap: 68   Dream    :124   1st Qu.:39.23   1st Qu.:15.60  
##  Gentoo   :124   Torgersen: 52   Median :44.45   Median :17.30  
##                                  Mean   :43.92   Mean   :17.15  
##                                  3rd Qu.:48.50   3rd Qu.:18.70  
##                                  Max.   :59.60   Max.   :21.50  
##                                  NA&amp;#39;s   :2       NA&amp;#39;s   :2      
##  flipper_length_mm  body_mass_g       sex           year     
##  Min.   :172.0     Min.   :2700   female:165   Min.   :2007  
##  1st Qu.:190.0     1st Qu.:3550   male  :168   1st Qu.:2007  
##  Median :197.0     Median :4050   NA&amp;#39;s  : 11   Median :2008  
##  Mean   :200.9     Mean   :4202                Mean   :2008  
##  3rd Qu.:213.0     3rd Qu.:4750                3rd Qu.:2009  
##  Max.   :231.0     Max.   :6300                Max.   :2009  
##  NA&amp;#39;s   :2         NA&amp;#39;s   :2&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this post, we will focus on the following three variables:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;species&lt;/code&gt;: the species of the penguin (Adelie, Chinstrap or Gentoo)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;sex&lt;/code&gt;: sex of the penguin (female and male)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;body_mass_g&lt;/code&gt;: body mass of the penguin (in grams)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If needed, more information about this dataset can be found by running &lt;code&gt;?penguins&lt;/code&gt; in R.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;body_mass_g&lt;/code&gt; is the quantitative continuous variable and will be the dependent variable, whereas &lt;code&gt;species&lt;/code&gt; and &lt;code&gt;sex&lt;/code&gt; are both qualitative variables.&lt;/p&gt;
&lt;p&gt;Those two last variables will be our independent variables, also referred as factors. Make sure that they are read as &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#factor&#34;&gt;factors&lt;/a&gt; by R. If it is not the case, they will need to be &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/#factors&#34;&gt;transformed to factors&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;aim-and-hypotheses-of-a-two-way-anova&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Aim and hypotheses of a two-way ANOVA&lt;/h1&gt;
&lt;p&gt;As mentioned above, a two-way ANOVA is used to &lt;strong&gt;evaluate simultaneously the effect of two categorical variables on one quantitative continuous variable&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;It is referred as &lt;strong&gt;two&lt;/strong&gt;-way ANOVA because we are comparing groups which are formed by &lt;strong&gt;two&lt;/strong&gt; independent categorical variables.&lt;/p&gt;
&lt;p&gt;Here, we would like to know if body mass depends on species and/or sex. In particular, we are interested in:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;measuring and testing the relationship between species and body mass,&lt;/li&gt;
&lt;li&gt;measuring and testing the relationship between sex and body mass, and&lt;/li&gt;
&lt;li&gt;potentially check whether the relationship between species and body mass is different for females and males (which is equivalent than checking whether the relationship between sex and body mass depends on the species)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The first two relationships are referred as &lt;strong&gt;main effects&lt;/strong&gt;, while the third point is known as the &lt;strong&gt;interaction effect&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The main effects test whether at least one group is different from another one (while controlling for the other independent variable). On the other hand, the interaction effect aims at testing whether the relationship between two variables differs &lt;em&gt;depending on the level of a third variable&lt;/em&gt;. In other words, if the evolution between the response and the first categorical variable does not depend on the modalities of the second categorical variable, then there is no interaction between the two variables. If, on the contrary, there is a modification of this evolution, either by an increase in the effect of the first variable, or by a decrease, then there is an interaction.&lt;/p&gt;
&lt;p&gt;When performing a two-way ANOVA, testing the interaction effect is not mandatory. However, omitting an interaction effect may lead to erroneous conclusions if the interaction effect is present.&lt;/p&gt;
&lt;p&gt;If we go back to our example, we have the following &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Main effect of sex on body mass:
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: mean body mass is equal between females and males&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: mean body mass is different between females and males&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Main effect of species on body mass:
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: mean body mass is equal between all 3 species&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: mean body mass is different for at least one species&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Interaction between sex and species:
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: there is no interaction between sex and species, meaning that the relationship between species and body mass is the same for females and males (similarly, the relationship between sex and body mass is the same for all 3 species)&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: there is an interaction between sex and species, meaning that the relationship between species and body mass is different for females than for males (similarly, the relationship between sex and body mass depends on the species)&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;assumptions-of-a-two-way-anova&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Assumptions of a two-way ANOVA&lt;/h1&gt;
&lt;p&gt;Most statistical tests require some assumptions for the results to be valid, and a two-way ANOVA is not an exception.&lt;/p&gt;
&lt;p&gt;Assumptions of a two-way ANOVA are similar than for a one-way ANOVA. To summarize:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Variable type&lt;/strong&gt;: the dependent variable must be quantitative continuous, while the two independent variables must be categorical (with at least two levels).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Independence&lt;/strong&gt;: the observations should be independent between groups and within each group.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Normality&lt;/strong&gt;:
&lt;ul&gt;
&lt;li&gt;For small samples, data should follow approximately a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;For large samples (usually &lt;span class=&#34;math inline&#34;&gt;\(n \ge 30\)&lt;/span&gt; in each group/sample), normality is not required (thanks to the central limit theorem)&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Equality of variances&lt;/strong&gt;: variances should be equal across groups.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Outliers&lt;/strong&gt;: There should be no significant &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt; in any group.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;More details about these assumptions can be found in the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#underlying-assumptions-of-anova&#34;&gt;assumptions of a one-way ANOVA&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Now that we have seen the underlying assumptions of the two-way ANOVA, we review them specifically for our dataset before applying the test and interpreting the results.&lt;/p&gt;
&lt;div id=&#34;variable-type&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Variable type&lt;/h2&gt;
&lt;p&gt;The dependent variable body mass is &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#continuous&#34;&gt;quantitative continuous&lt;/a&gt;, while both independent variables sex and species are &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;qualitative variables&lt;/a&gt; (with at least 2 levels).&lt;/p&gt;
&lt;p&gt;Therefore, this assumption is met.&lt;/p&gt;
&lt;p&gt;If your dependent variable is &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#discrete&#34;&gt;quantitative discrete&lt;/a&gt;, this is count data, which, strictly speaking, should be analyzed using a generalized linear model, not an ANOVA.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;independence&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Independence&lt;/h2&gt;
&lt;p&gt;Independence is usually checked based on the design of the experiment and how data have been collected.&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;To keep it simple, observations are usually:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;independent&lt;/strong&gt; if each experimental unit (here a penguin) has been measured only once and the observations are collected from a representative and randomly selected portion of the population, or&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;dependent&lt;/strong&gt; if each experimental unit has been measured at least twice (as it is often the case in the medical field for example, with two measurements on the same subjects; one before and one after the treatment).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In our case, body mass has been measured only once on each penguin, and on a representative and random sample of the population, so the independence assumption is met.&lt;/p&gt;
&lt;p&gt;Note that if your data correspond to observations made several times on the same experimental units (for example, if one of the factors is a treatment (A or B) and the second factor is time (day 1, day 2 and day 3), and measurements are made at each time point on the same subjects), a two-way &lt;em&gt;mixed&lt;/em&gt; ANOVA should be used.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;normality&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Normality&lt;/h2&gt;
&lt;p&gt;We have a large sample in all subgroups (each combination of the levels of the two factors, called cell):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;table(dat$species, dat$sex)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##            
##             female male
##   Adelie        73   73
##   Chinstrap     34   34
##   Gentoo        58   61&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;so normality does not need to be checked.&lt;/p&gt;
&lt;p&gt;For completeness, we still show how to verify normality, as if we had a small samples.&lt;/p&gt;
&lt;p&gt;There are several methods to test the normality assumption. The most common methods being:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#qq-plot&#34;&gt;QQ-plot&lt;/a&gt; by group or on the residuals, and/or&lt;/li&gt;
&lt;li&gt;a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt; by group or on the residuals, and/or&lt;/li&gt;
&lt;li&gt;a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#normality-test&#34;&gt;normality test&lt;/a&gt; (Shapiro-Wilk test for instance) by group or on the residuals.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The easiest/shortest way is to verify the normality with a QQ-plot on the residuals. To draw this plot, we first need to save the model:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# save model
mod &amp;lt;- aov(body_mass_g ~ sex * species,
  data = dat
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This piece of code will be explained further.&lt;/p&gt;
&lt;p&gt;Now we can draw the QQ-plot on the residuals. We show two ways to do so, first with the &lt;code&gt;plot()&lt;/code&gt; function and second with the &lt;code&gt;qqPlot()&lt;/code&gt; function from the &lt;code&gt;{car}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# method 1
plot(mod, which = 2)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-5-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# method 2
library(car)

qqPlot(mod$residuals,
  id = FALSE # remove point identification
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-5-2.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Code for method 1 is slightly shorter, but it misses the confidence interval around the reference line.&lt;/p&gt;
&lt;p&gt;If points follow the straight line (called Henry’s line) and fall within the confidence band, we can assume normality. This is the case here.&lt;/p&gt;
&lt;p&gt;If you prefer to verify the normality based on a histogram of the residuals, here is the code:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# histogram
hist(mod$residuals)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-6-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The histogram of the residuals show a gaussian distribution, which is in line with the conclusion from the QQ-plot.&lt;/p&gt;
&lt;p&gt;Although the QQ-plot and histogram is largely enough to verify the normality, if you want to test it more formally with a statistical test, the Shapiro-Wilk test can be applied on the residuals as well:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# normality test
shapiro.test(mod$residuals)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Shapiro-Wilk normality test
## 
## data:  mod$residuals
## W = 0.99776, p-value = 0.9367&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(\Rightarrow\)&lt;/span&gt; We do not reject the null hypothesis that the residuals follow a normal distribution (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.937).&lt;/p&gt;
&lt;p&gt;From the QQ-plot, histogram and Shapiro-Wilk test, we conclude that we do not reject the null hypothesis of normality of the residuals.&lt;/p&gt;
&lt;p&gt;The normality assumption is thus verified, we can now check the equality of the variances.&lt;/p&gt;
&lt;p&gt;Note that if the normality assumption is not met, many transformations can be applied on the dependent variable to improve it, the most common ones being the logarithmic (&lt;code&gt;log()&lt;/code&gt; function in R) and the Box-Cox transformations. If the normality assumption is still not met on the transformed data, the non-parametric version of the two-way ANOVA, the &lt;a href=&#34;https://rcompanion.org/handbook/F_14.html&#34; target=&#34;_blank&#34;&gt;Scheirer–Ray–Hare test&lt;/a&gt;, can be used. Alternatively, a permutation test can also be used.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;homogeneity-of-variances&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Homogeneity of variances&lt;/h2&gt;
&lt;p&gt;Equality of variances, also referred as homogeneity of variances or homoscedasticity, can be verified visually with the &lt;code&gt;plot()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(mod, which = 3)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-8-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Since the spread of the residuals is constant, the red smooth line is horizontal and flat, so it looks like the constant variance assumption is satisfied here.&lt;/p&gt;
&lt;p&gt;The diagnostic plot above is sufficient, but if you prefer it can also be tested more formally with the Levene’s test (also from the &lt;code&gt;{car}&lt;/code&gt; package):&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;leveneTest(mod)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Levene&amp;#39;s Test for Homogeneity of Variance (center = median)
##        Df F value Pr(&amp;gt;F)
## group   5  1.3908 0.2272
##       327&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(\Rightarrow\)&lt;/span&gt; We do not reject the null hypothesis that the variances are equal (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.227).&lt;/p&gt;
&lt;p&gt;Both the visual and formal approaches give the same conclusion; we do not reject the hypothesis of homogeneity of the variances.&lt;/p&gt;
&lt;p&gt;Note that, as for the normality, the logarithmic and Box-Cox transformations may improve homogeneity of the residuals.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;outliers&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Outliers&lt;/h2&gt;
&lt;p&gt;The easiest and most common way to &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;detect outliers&lt;/a&gt; is visually thanks to boxplots by groups.&lt;/p&gt;
&lt;p&gt;For females and males:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggplot2)

# boxplots by sex
ggplot(dat) +
  aes(x = sex, y = body_mass_g) +
  geom_boxplot()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-10-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;For the three species:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# boxplots by species
ggplot(dat) +
  aes(x = species, y = body_mass_g) +
  geom_boxplot()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-11-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;There are, as defined by the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#interquartile-range&#34;&gt;interquartile range criterion&lt;/a&gt;, two outliers for the species Chinstrap. These points are, nonetheless, not extreme enough to bias results.&lt;/p&gt;
&lt;p&gt;Therefore, we consider that the assumption of no significant outliers is met.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;two-way-anova&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Two-way ANOVA&lt;/h1&gt;
&lt;p&gt;We have shown that all assumptions are met, so we can now proceed to the implementation of the two-way ANOVA in R.&lt;/p&gt;
&lt;p&gt;This will allow us to answer the following research questions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Controlling for the species, is body mass significantly different between the two sexes?&lt;/li&gt;
&lt;li&gt;Controlling for the sex, is body mass significantly different for at least one species?&lt;/li&gt;
&lt;li&gt;Is the relationship between species and body mass different between female and male penguins?&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&#34;preliminary-analyses&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Preliminary analyses&lt;/h2&gt;
&lt;p&gt;Before performing any statistical test, it is a good practice to make some &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt; in order to have a first overview of the data, and perhaps, have a glimpse of the results to be expected.&lt;/p&gt;
&lt;p&gt;This can be done via descriptive statistics or plots.&lt;/p&gt;
&lt;div id=&#34;descriptive-statistics&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Descriptive statistics&lt;/h3&gt;
&lt;p&gt;If we want to keep it simple, we can compute only the mean for each subgroup:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# mean by group
aggregate(body_mass_g ~ species + sex,
  data = dat,
  FUN = mean
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##     species    sex body_mass_g
## 1    Adelie female    3368.836
## 2 Chinstrap female    3527.206
## 3    Gentoo female    4679.741
## 4    Adelie   male    4043.493
## 5 Chinstrap   male    3938.971
## 6    Gentoo   male    5484.836&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Or eventually, the mean and &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#standard-deviation&#34;&gt;standard deviation&lt;/a&gt; for each subgroup using the &lt;code&gt;{dplyr}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# mean and sd by group
library(dplyr)

group_by(dat, sex, species) %&amp;gt;%
  summarise(
    mean = round(mean(body_mass_g, na.rm = TRUE)),
    sd = round(sd(body_mass_g, na.rm = TRUE))
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 8 × 4
## # Groups:   sex [3]
##   sex    species    mean    sd
##   &amp;lt;fct&amp;gt;  &amp;lt;fct&amp;gt;     &amp;lt;dbl&amp;gt; &amp;lt;dbl&amp;gt;
## 1 female Adelie     3369   269
## 2 female Chinstrap  3527   285
## 3 female Gentoo     4680   282
## 4 male   Adelie     4043   347
## 5 male   Chinstrap  3939   362
## 6 male   Gentoo     5485   313
## 7 &amp;lt;NA&amp;gt;   Adelie     3540   477
## 8 &amp;lt;NA&amp;gt;   Gentoo     4588   338&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;plots&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Plots&lt;/h3&gt;
&lt;p&gt;If you are a frequent reader of the blog, you know that I like to draw plots to visualize the data at hand before interpreting results of a test.&lt;/p&gt;
&lt;p&gt;The most appropriate plot when we have one quantitative and two qualitative variables is a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#boxplot&#34;&gt;boxplot&lt;/a&gt; by group. This can easily be made with the &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;&lt;code&gt;{ggplot2}&lt;/code&gt; package&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# boxplot by group
library(ggplot2)

ggplot(dat) +
  aes(x = species, y = body_mass_g, fill = sex) +
  geom_boxplot()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-14-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Some observations are missing for the sex, we can remove them to have a more concise plot:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat %&amp;gt;%
  filter(!is.na(sex)) %&amp;gt;%
  ggplot() +
  aes(x = species, y = body_mass_g, fill = sex) +
  geom_boxplot()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-15-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Note that we could also have made the following plot:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat %&amp;gt;%
  filter(!is.na(sex)) %&amp;gt;%
  ggplot() +
  aes(x = sex, y = body_mass_g, fill = species) +
  geom_boxplot()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-16-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;But for a more readable plot, I tend to prefer putting the variable with the smallest number of levels as color (which is in fact the argument &lt;code&gt;fill&lt;/code&gt; in the &lt;code&gt;aes()&lt;/code&gt; layer) and the variable with the largest number of categories on the x-axis (i.e., the argument &lt;code&gt;x&lt;/code&gt; in the &lt;code&gt;aes()&lt;/code&gt; layer).&lt;/p&gt;
&lt;p&gt;From the means and the boxplots by subgroup, we can already see that, &lt;em&gt;in our sample&lt;/em&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;female penguins tend to have a lower body mass than males, and that is the case for all the considered species, and&lt;/li&gt;
&lt;li&gt;body mass is higher for Gentoo penguins than for the other two species.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Bear in mind that these conclusions are only valid within our &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;sample&lt;/a&gt;! To generalize these conclusions to the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;population&lt;/a&gt;, we need to perform the two-way ANOVA and check the significance of the explanatory variables. This is the aim of the next section.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;two-way-anova-in-r&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Two-way ANOVA in R&lt;/h2&gt;
&lt;p&gt;As mentioned earlier, including an interaction effect in a two-way ANOVA is not compulsory. However, in order to avoid flawed conclusions, it is recommended to first check whether the interaction is significant or not, and depending on the results, include it or not.&lt;/p&gt;
&lt;p&gt;If the interaction is not significant, it is safe to remove it from the final model. On the contrary, if the interaction is significant, it should be included in the final model which will be used to interpret results.&lt;/p&gt;
&lt;p&gt;We thus start with a model which includes the two main effects (i.e., sex and species) and the interaction:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Two-way ANOVA with interaction
# save model
mod &amp;lt;- aov(body_mass_g ~ sex * species,
  data = dat
)

# print results
summary(mod)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##              Df    Sum Sq  Mean Sq F value   Pr(&amp;gt;F)    
## sex           1  38878897 38878897 406.145  &amp;lt; 2e-16 ***
## species       2 143401584 71700792 749.016  &amp;lt; 2e-16 ***
## sex:species   2   1676557   838278   8.757 0.000197 ***
## Residuals   327  31302628    95727                     
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 11 observations deleted due to missingness&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Similar to a one-way ANOVA, the principle of a two-way ANOVA is based on the total dispersion of the data, and its decomposition into four components:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;the share attributable to the first factor&lt;/li&gt;
&lt;li&gt;the share attributable to the second factor&lt;/li&gt;
&lt;li&gt;the share attributable to the interaction of the 2 factors&lt;/li&gt;
&lt;li&gt;the unexplained, or residual portion.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The sum of squares (column &lt;code&gt;Sum Sq&lt;/code&gt;) shows these four components. The two-way ANOVA consists of using a statistical test to determine whether each of the dispersion component (attributable to the 2 factors studied and to their interaction) is significantly greater than the residual component. If this is the case, we conclude that the effect considered (factor A, factor B or the interaction) is significant.&lt;/p&gt;
&lt;p&gt;We see that the species explain a large part of the variability of body mass. It is the most important factor in explaining this variability.&lt;/p&gt;
&lt;p&gt;The &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values are displayed in the last column of the output above (&lt;code&gt;Pr(&amp;gt;F)&lt;/code&gt;). From these &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values, we conclude that, at the 5% significance level:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;controlling for the species, body mass is significantly different between the two sexes,&lt;/li&gt;
&lt;li&gt;controlling for the sex, body mass is significantly different for at least one species, and&lt;/li&gt;
&lt;li&gt;the interaction between sex and species (displayed at the line &lt;code&gt;sex:species&lt;/code&gt; in the output above) is significant.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So from the significant interaction effect, we have just seen that the relationship between body mass and species is different between males and females. Since it is significant, we have to keep it in the model and we should interpret results from that model.&lt;/p&gt;
&lt;p&gt;If, on the contrary, the interaction was not significant (that is, if the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &lt;span class=&#34;math inline&#34;&gt;\(\ge\)&lt;/span&gt; 0.05) we would have removed this interaction effect from the model. For illustrative purposes, below the code for a two-way ANOVA without interaction, referred as an additive model:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Two-way ANOVA without interaction
aov(body_mass_g ~ sex + species,
  data = dat
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For the readers who are used to perform &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;linear regressions in R&lt;/a&gt;, you will notice that the structure of the code for a two-way ANOVA is in fact similar:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the formula is &lt;code&gt;dependent variable ~ independent variables&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;the &lt;code&gt;+&lt;/code&gt; sign is used to include independent variables &lt;em&gt;without&lt;/em&gt; an interaction&lt;a href=&#34;#fn4&#34; class=&#34;footnote-ref&#34; id=&#34;fnref4&#34;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;the &lt;code&gt;*&lt;/code&gt; sign is used to include independent variables &lt;em&gt;with&lt;/em&gt; an interaction&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The resemblance with a linear regression is not a surprise because a two-way ANOVA, like all ANOVA, is actually a linear model.&lt;/p&gt;
&lt;p&gt;Note that the following code works as well, and give the same results:&lt;a href=&#34;#fn5&#34; class=&#34;footnote-ref&#34; id=&#34;fnref5&#34;&gt;&lt;sup&gt;5&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# method 2
mod2 &amp;lt;- lm(body_mass_g ~ sex * species,
  data = dat
)

Anova(mod2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Anova Table (Type II tests)
## 
## Response: body_mass_g
##                Sum Sq  Df F value    Pr(&amp;gt;F)    
## sex          37090262   1 387.460 &amp;lt; 2.2e-16 ***
## species     143401584   2 749.016 &amp;lt; 2.2e-16 ***
## sex:species   1676557   2   8.757 0.0001973 ***
## Residuals    31302628 327                      
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the &lt;code&gt;aov()&lt;/code&gt; function assumes a &lt;strong&gt;balanced design&lt;/strong&gt;, meaning that we have equal sample sizes within levels of our independent grouping variables. Moreover, &lt;code&gt;aov()&lt;/code&gt; uses the type I sums of squares, so we can obtain different &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values when we write &lt;code&gt;y ~ A * B&lt;/code&gt; and &lt;code&gt;y ~ B * A&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;For &lt;strong&gt;unbalanced design&lt;/strong&gt;, that is, unequal numbers of subjects in each subgroup, the recommended methods are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the type II ANOVA when there is &lt;strong&gt;no&lt;/strong&gt; significant interaction, which can be done in R with &lt;code&gt;Anova(mod, type = &#34;II&#34;)&lt;/code&gt; or &lt;code&gt;Anova(mod, type = 2)&lt;/code&gt;, where &lt;code&gt;mod&lt;/code&gt; is the name of your saved model, and&lt;/li&gt;
&lt;li&gt;the type III ANOVA when there is a significant interaction, which can be done in R with &lt;code&gt;Anova(mod, type = &#34;III&#34;)&lt;/code&gt; or &lt;code&gt;Anova(mod, type = 3)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This is beyond the scope of the post and we assume a balanced design here. For the interested reader, see this &lt;a href=&#34;https://mcfromnz.wordpress.com/2011/03/02/anova-type-iiiiii-ss-explained/&#34; target=&#34;_blank&#34;&gt;detailed discussion&lt;/a&gt; about type I, type II and type III ANOVA.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;pairwise-comparisons&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Pairwise comparisons&lt;/h2&gt;
&lt;p&gt;Through the two main effects being significant, we concluded that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;controlling for the species, body mass is different between females and males, and&lt;/li&gt;
&lt;li&gt;controlling for the sex, body mass is different for at least one species.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If body mass is different between the two sexes, given that there are exactly two sexes, it must be because body mass is significantly different between females and males.&lt;/p&gt;
&lt;p&gt;If one wants to know which sex has the highest body mass, it can be deduced from the means and/or boxplots by subgroup. Here, it is clear that males have a significantly higher body mass than females.&lt;/p&gt;
&lt;p&gt;However, it is not so straightforward for the species. Let me explain why it is not as easy as for the sexes.&lt;/p&gt;
&lt;p&gt;There are three species (Adelie, Chinstrap and Gentoo), so there are 3 pairs of species:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Adelie and Chinstrap&lt;/li&gt;
&lt;li&gt;Adelie and Gentoo&lt;/li&gt;
&lt;li&gt;Chinstrap and Gentoo&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;If body mass is significantly different for at least one species, it could be that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;body mass is significantly different between Adelie and Chinstrap but not significantly different between Adelie and Gentoo, and not significantly different between Chinstrap and Gentoo, or&lt;/li&gt;
&lt;li&gt;body mass is significantly different between Adelie and Gentoo but not significantly different between Adelie and Chinstrap, and not significantly different between Chinstrap and Gentoo, or&lt;/li&gt;
&lt;li&gt;body mass is significantly different between Chinstrap and Gentoo but not significantly different between Adelie and Chinstrap, and not significantly different between Adelie and Gentoo.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Or, it could also be that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;body mass is significantly different between Adelie and Chinstrap, and between Adelie and Gentoo, but not significantly different between Chinstrap and Gentoo, or&lt;/li&gt;
&lt;li&gt;body mass is significantly different between Adelie and Chinstrap, and between Chinstrap and Gentoo, but not significantly different between Adelie and Gentoo, or&lt;/li&gt;
&lt;li&gt;body mass is significantly different between Chinstrap and Gentoo, and between Adelie and Gentoo, but not significantly different between Adelie and Chinstrap.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Last, it could also be that body mass is significantly different between &lt;strong&gt;all&lt;/strong&gt; species.&lt;/p&gt;
&lt;p&gt;As for a &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;one-way ANOVA&lt;/a&gt;, we cannot, at this stage, know precisely which species is different from which one in terms of body mass. To know this, we need to compare each species two by two thanks to post-hoc tests (also known as pairwise comparisons).&lt;/p&gt;
&lt;p&gt;There are several post-hoc tests, the most common ones being the Tukey HSD which tests all possible pairs of groups, and the Dunett’s test which compares all groups to a reference group. As mentioned earlier, these tests should not be done on the sex variable because there are only two levels.&lt;/p&gt;
&lt;p&gt;In this post, we show only the Tukey HSD test. For the interested reader, the Dunnett’s test is illustrated &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#dunnetts-test&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;As for the one-way ANOVA, the Tukey HSD test can be done in R as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# method 1
TukeyHSD(mod,
  which = &amp;quot;species&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   Tukey multiple comparisons of means
##     95% family-wise confidence level
## 
## Fit: aov(formula = body_mass_g ~ sex * species, data = dat)
## 
## $species
##                        diff       lwr       upr     p adj
## Chinstrap-Adelie   26.92385  -80.0258  133.8735 0.8241288
## Gentoo-Adelie    1377.65816 1287.6926 1467.6237 0.0000000
## Gentoo-Chinstrap 1350.73431 1239.9964 1461.4722 0.0000000&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or using the &lt;code&gt;{multcomp}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# method 2
library(multcomp)

res_tukey &amp;lt;- glht(
  aov(body_mass_g ~ sex + species,
    data = dat
  ),
  linfct = mcp(species = &amp;quot;Tukey&amp;quot;)
)

summary(res_tukey)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	 Simultaneous Tests for General Linear Hypotheses
## 
## Multiple Comparisons of Means: Tukey Contrasts
## 
## 
## Fit: aov(formula = body_mass_g ~ sex + species, data = dat)
## 
## Linear Hypotheses:
##                         Estimate Std. Error t value Pr(&amp;gt;|t|)    
## Chinstrap - Adelie == 0    26.92      46.48   0.579     0.83    
## Gentoo - Adelie == 0     1377.86      39.10  35.236   &amp;lt;1e-05 ***
## Gentoo - Chinstrap == 0  1350.93      48.13  28.067   &amp;lt;1e-05 ***
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## (Adjusted p values reported -- single-step method)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or using the &lt;code&gt;pairwise.t.test()&lt;/code&gt; function using the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value adjustment method of your choice:&lt;a href=&#34;#fn6&#34; class=&#34;footnote-ref&#34; id=&#34;fnref6&#34;&gt;&lt;sup&gt;6&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# method 3
pairwise.t.test(dat$body_mass_g, dat$species,
  p.adjust.method = &amp;quot;BH&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Pairwise comparisons using t tests with pooled SD 
## 
## data:  dat$body_mass_g and dat$species 
## 
##           Adelie Chinstrap
## Chinstrap 0.63   -        
## Gentoo    &amp;lt;2e-16 &amp;lt;2e-16   
## 
## P value adjustment method: BH&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that when using the second method, it is the model without the interaction that needs to be specified into the &lt;code&gt;glht()&lt;/code&gt; function, even if the interaction is significant. Moreover, do not forget to replace &lt;code&gt;mod&lt;/code&gt; and &lt;code&gt;species&lt;/code&gt; in my code with the name of your model and the name of your independent variable.&lt;/p&gt;
&lt;p&gt;Both methods give the same results, that is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;body mass is &lt;em&gt;not&lt;/em&gt; significantly different between Chinstrap and Adelie (adjusted &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.83),&lt;/li&gt;
&lt;li&gt;body mass is significantly different between Gentoo and Adelie (adjusted &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &amp;lt; 0.001), and&lt;/li&gt;
&lt;li&gt;body mass is significantly different between Gentoo and Chinstrap (adjusted &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &amp;lt; 0.001).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Remember that it is the &lt;strong&gt;adjusted&lt;/strong&gt; &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values that are reported, to prevent the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#issue-of-multiple-testing&#34;&gt;issue of multiple testing&lt;/a&gt; which occurs when comparing several pairs of groups.&lt;/p&gt;
&lt;p&gt;If you would like to compare all combinations of groups, it can be done with the &lt;code&gt;TukeyHSD()&lt;/code&gt; function and specifying the interaction in the &lt;code&gt;which&lt;/code&gt; argument:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# all combinations of sex and species
TukeyHSD(mod,
  which = &amp;quot;sex:species&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   Tukey multiple comparisons of means
##     95% family-wise confidence level
## 
## Fit: aov(formula = body_mass_g ~ sex * species, data = dat)
## 
## $`sex:species`
##                                      diff       lwr       upr     p adj
## male:Adelie-female:Adelie        674.6575  527.8486  821.4664 0.0000000
## female:Chinstrap-female:Adelie   158.3703  -25.7874  342.5279 0.1376213
## male:Chinstrap-female:Adelie     570.1350  385.9773  754.2926 0.0000000
## female:Gentoo-female:Adelie     1310.9058 1154.8934 1466.9181 0.0000000
## male:Gentoo-female:Adelie       2116.0004 1962.1408 2269.8601 0.0000000
## female:Chinstrap-male:Adelie    -516.2873 -700.4449 -332.1296 0.0000000
## male:Chinstrap-male:Adelie      -104.5226 -288.6802   79.6351 0.5812048
## female:Gentoo-male:Adelie        636.2482  480.2359  792.2606 0.0000000
## male:Gentoo-male:Adelie         1441.3429 1287.4832 1595.2026 0.0000000
## male:Chinstrap-female:Chinstrap  411.7647  196.6479  626.8815 0.0000012
## female:Gentoo-female:Chinstrap  1152.5355  960.9603 1344.1107 0.0000000
## male:Gentoo-female:Chinstrap    1957.6302 1767.8040 2147.4564 0.0000000
## female:Gentoo-male:Chinstrap     740.7708  549.1956  932.3460 0.0000000
## male:Gentoo-male:Chinstrap      1545.8655 1356.0392 1735.6917 0.0000000
## male:Gentoo-female:Gentoo        805.0947  642.4300  967.7594 0.0000000&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Or with the &lt;code&gt;HSD.test()&lt;/code&gt; function from the &lt;code&gt;{agricolae}&lt;/code&gt; package, which denotes subgroups that are not significantly different from each other with the same letter:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(agricolae)

HSD.test(mod,
  trt = c(&amp;quot;sex&amp;quot;, &amp;quot;species&amp;quot;),
  console = TRUE # print results
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Study: mod ~ c(&amp;quot;sex&amp;quot;, &amp;quot;species&amp;quot;)
## 
## HSD Test for body_mass_g 
## 
## Mean Square Error:  95726.69 
## 
## sex:species,  means
## 
##                  body_mass_g      std  r  Min  Max
## female:Adelie       3368.836 269.3801 73 2850 3900
## female:Chinstrap    3527.206 285.3339 34 2700 4150
## female:Gentoo       4679.741 281.5783 58 3950 5200
## male:Adelie         4043.493 346.8116 73 3325 4775
## male:Chinstrap      3938.971 362.1376 34 3250 4800
## male:Gentoo         5484.836 313.1586 61 4750 6300
## 
## Alpha: 0.05 ; DF Error: 327 
## Critical Value of Studentized Range: 4.054126 
## 
## Groups according to probability of means differences and alpha level( 0.05 )
## 
## Treatments with the same letter are not significantly different.
## 
##                  body_mass_g groups
## male:Gentoo         5484.836      a
## female:Gentoo       4679.741      b
## male:Adelie         4043.493      c
## male:Chinstrap      3938.971      c
## female:Chinstrap    3527.206      d
## female:Adelie       3368.836      d&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you have many groups to compare, plotting them might be easier to interpret:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# set axis margins so labels do not get cut off
par(mar = c(4.1, 13.5, 4.1, 2.1))

# create confidence interval for each comparison
plot(TukeyHSD(mod, which = &amp;quot;sex:species&amp;quot;),
  las = 2 # rotate x-axis ticks
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-25-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;From the outputs and plot above, we conclude that all combinations of sex and species are significantly different, except between female Chinstrap and female Adelie (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.138) and male Chinstrap and male Adelie (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.581).&lt;/p&gt;
&lt;p&gt;These results, which are by the way in line with the boxplots shown above and which will be confirmed with the visualizations below, concludes the two-way ANOVA in R.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;visualizations&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Visualizations&lt;/h2&gt;
&lt;p&gt;If you would like to visualize results in a different way to what has already been presented in the preliminary analyses, below are some ideas of useful plots.&lt;/p&gt;
&lt;p&gt;First, with the mean and standard error of the mean by subgroup using the &lt;code&gt;allEffects()&lt;/code&gt; function from the &lt;code&gt;{effects}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# method 1
library(effects)

plot(allEffects(mod))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-26-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Or using the &lt;code&gt;{ggpubr}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# method 2
library(ggpubr)

ggline(subset(dat, !is.na(sex)), # remove NA level for sex
  x = &amp;quot;species&amp;quot;,
  y = &amp;quot;body_mass_g&amp;quot;,
  color = &amp;quot;sex&amp;quot;,
  add = c(&amp;quot;mean_se&amp;quot;) # add mean and standard error
) +
  labs(y = &amp;quot;Mean of body mass (g)&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-27-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Alternatively, using &lt;code&gt;{Rmisc}&lt;/code&gt; and &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(Rmisc)

# compute mean and standard error of the mean by subgroup
summary_stat &amp;lt;- summarySE(dat,
  measurevar = &amp;quot;body_mass_g&amp;quot;,
  groupvars = c(&amp;quot;species&amp;quot;, &amp;quot;sex&amp;quot;)
)

# plot mean and standard error of the mean
ggplot(
  subset(summary_stat, !is.na(sex)), # remove NA level for sex
  aes(x = species, y = body_mass_g, colour = sex)
) +
  geom_errorbar(aes(ymin = body_mass_g - se, ymax = body_mass_g + se), # add error bars
    width = 0.1 # width of error bars
  ) +
  geom_point() +
  labs(y = &amp;quot;Mean of body mass (g)&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-28-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Second, if you prefer to draw only the mean by subgroup:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;with(
  dat,
  interaction.plot(species, sex, body_mass_g)
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-29-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Last but not least, for those of you who are familiar with GraphPad, you are most likely familiar with plotting means and error bars as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# plot mean and standard error of the mean as barplots
ggplot(
  subset(summary_stat, !is.na(sex)), # remove NA level for sex
  aes(x = species, y = body_mass_g, fill = sex)
) +
  geom_bar(position = position_dodge(), stat = &amp;quot;identity&amp;quot;) +
  geom_errorbar(aes(ymin = body_mass_g - se, ymax = body_mass_g + se), # add error bars
    width = 0.25, # width of error bars
    position = position_dodge(.9)
  ) +
  labs(y = &amp;quot;Mean of body mass (g)&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/two-way-anova-in-r/index_files/figure-html/unnamed-chunk-30-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;In this post, we started with a few reminders of the different tests that exist to compare a quantitative variable across groups. We then focused on the two-way ANOVA, starting from its goal and hypotheses to its implementation in R, together with the interpretations and some visualizations. We also briefly mentioned its underlying assumptions and one post-hoc test to compare all subgroups.&lt;/p&gt;
&lt;p&gt;All this was illustrated with the &lt;code&gt;penguins&lt;/code&gt; dataset available from the &lt;code&gt;{palmerpenguins}&lt;/code&gt; package.&lt;/p&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article will help you in conducting a two-way ANOVA with your data.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;In theory, a one-way ANOVA can also be used to compare 2 groups, and not only 3 or more. Nonetheless, in practice, it is often the case that a Student’s t-test is performed to compare 2 groups, and a one-way ANOVA to compare 3 or more groups. Conclusions obtained via a Student’s t-test for independent samples and a one-way ANOVA with 2 groups will be similar.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;If you really want to test the independence, you can do so visually with a plot of the residuals vs. fitted values. This plot can be done in R with &lt;code&gt;plot(mod, which = 1)&lt;/code&gt;, where &lt;code&gt;mod&lt;/code&gt; corresponds to the name of your model. Or you can do so with the Durbin-Watson test. In R, it can be done with the &lt;code&gt;durbinWatsonTest()&lt;/code&gt; function from the &lt;code&gt;{car}&lt;/code&gt; package.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;Note that the Bartlett’s and Fligner-Killeen tests are also appropriate to test the assumption of equal variances.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;An additive model makes the assumption that the 2 explanatory variables are independent; they do not interact with each other.&lt;a href=&#34;#fnref4&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn5&#34;&gt;&lt;p&gt;To not be confused with the &lt;code&gt;anova()&lt;/code&gt; function because it provides sequential results that depend on the order in which the variables appear in the model.&lt;a href=&#34;#fnref5&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn6&#34;&gt;&lt;p&gt;Here, we use the Benjamini &amp;amp; Hochberg (1995) correction, but you can choose between several methods. See &lt;code&gt;?p.adjust&lt;/code&gt; for more details.&lt;a href=&#34;#fnref6&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>What is survival analysis? Examples by hand and in R</title>
      <link>https://statsandr.com/blog/what-is-survival-analysis/</link>
      <pubDate>Thu, 22 Dec 2022 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/what-is-survival-analysis/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#what-is-survival-analysis&#34; id=&#34;toc-what-is-survival-analysis&#34;&gt;What is survival analysis?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#why-do-we-need-special-methods-for-survival-analysis&#34; id=&#34;toc-why-do-we-need-special-methods-for-survival-analysis&#34;&gt;Why do we need special methods for survival analysis?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#common-functions-in-survival-analysis&#34; id=&#34;toc-common-functions-in-survival-analysis&#34;&gt;Common functions in survival analysis&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#survival-function&#34; id=&#34;toc-survival-function&#34;&gt;Survival function&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#cumulative-hazard-function&#34; id=&#34;toc-cumulative-hazard-function&#34;&gt;Cumulative hazard function&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#hazard-function&#34; id=&#34;toc-hazard-function&#34;&gt;Hazard function&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#estimation&#34; id=&#34;toc-estimation&#34;&gt;Estimation&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand&#34; id=&#34;toc-by-hand&#34;&gt;By hand&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#in-r&#34; id=&#34;toc-in-r&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#hypothesis-testing&#34; id=&#34;toc-hypothesis-testing&#34;&gt;Hypothesis testing&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#log-rank-test&#34; id=&#34;toc-log-rank-test&#34;&gt;Log-rank test&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand-1&#34; id=&#34;toc-by-hand-1&#34;&gt;By hand&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#in-r-1&#34; id=&#34;toc-in-r-1&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#to-go-further&#34; id=&#34;toc-to-go-further&#34;&gt;To go further&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;images/what-is-survival-analysis.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note that this article is inspired from:&lt;/em&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;the lecture notes of Prof. Van Keilegom and my personal notes as teaching assistant for her course entitled “Analysis of Survival and Duration Data” given at UCLouvain&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;the lecture notes of Prof. Legrand for her course entitled “Statistics in clinical trials” given at UCLouvain&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;For the last post of the year, I would like to present a rather unknown (yet important) statistical method–&lt;strong&gt;survival analysis&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Although survival analysis is a branch of statistics, it is usually not covered in introductory statistics courses and it is rather unknown to the general public. It is mostly taught in biostatistics courses or advanced statistics study programs.&lt;/p&gt;
&lt;p&gt;In this article, I will explain what is survival analysis, in which context and how it is used. I will explain the main tools and methods used by biostatisticians to analyze survival data and how to estimate and interpret survival curves.&lt;/p&gt;
&lt;p&gt;I will show in detail how to apply these techniques in R with concrete examples. In practice, survival analysis is almost always done via a statistical program and never done by hand. However, as for any statistical concept, I believe that doing it by hand allows to really understand the concepts and what these programs actually do. For this reason, I will also show a brief example on how to perform a basic survival analysis by hand.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;what-is-survival-analysis&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;What is survival analysis?&lt;/h1&gt;
&lt;p&gt;&lt;strong&gt;Survival analysis&lt;/strong&gt; (also called time-to-event analysis or duration analysis) is a branch of statistics aimed at &lt;strong&gt;analyzing the duration of time from a well-defined time origin until one or more events happen&lt;/strong&gt;, called survival times or duration times.&lt;/p&gt;
&lt;p&gt;In other words, in survival analysis, we are interested in a certain event and want to &lt;strong&gt;analyze the time until the event happens&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;While the event of interest is often death (in this case we study the time to death for patients having a specific disease) or recurrence (in this case we study the time to relapse of a certain disease), it is not limited to the medical field or epidemiology.&lt;/p&gt;
&lt;p&gt;In fact, it can be used in many domains. For example, we may also analyze the time until:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;getting cured from a certain disease&lt;/li&gt;
&lt;li&gt;finding a new job after a period of unemployment&lt;/li&gt;
&lt;li&gt;being arrested again after having been released from jail&lt;/li&gt;
&lt;li&gt;the first pregnancy&lt;/li&gt;
&lt;li&gt;the failure of a mechanical system or a machine&lt;/li&gt;
&lt;li&gt;a bank or a company goes bankrupt&lt;/li&gt;
&lt;li&gt;a customer buys a new product or stops its current subscription&lt;/li&gt;
&lt;li&gt;a letter is delivered&lt;/li&gt;
&lt;li&gt;a taxi picks you up after having called the taxi company&lt;/li&gt;
&lt;li&gt;an employee leaves the company&lt;/li&gt;
&lt;li&gt;etc.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;As you can see, the event of interest does not necessarily have to be the death or the occurrence of a disease, but in all situations &lt;strong&gt;we are interested in analyzing the time until a specific event occurs&lt;/strong&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;why-do-we-need-special-methods-for-survival-analysis&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Why do we need special methods for survival analysis?&lt;/h1&gt;
&lt;p&gt;Survival data, also referred as time-to-event data, requires a special set of statistical methods for three main reasons:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Duration times&lt;/strong&gt; are &lt;strong&gt;always positive&lt;/strong&gt;: the time until an event of interest occurs cannot be less than 0. Moreover, the distribution of survival times is right-skewed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Different measures&lt;/strong&gt; are of interest depending on the research question, context, etc. For instance, we could be interested in:
&lt;ul&gt;
&lt;li&gt;The &lt;strong&gt;probability&lt;/strong&gt; that a cancer patient survives longer than 5 years after diagnosis?&lt;/li&gt;
&lt;li&gt;The typical &lt;strong&gt;waiting time&lt;/strong&gt; for a cab to arrive after having called the taxi company?&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;How many&lt;/strong&gt;, out of 100 unemployed people, are expected to have a job again after 2 months of unemployment?&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Censoring&lt;/strong&gt; is almost always an issue:
&lt;ul&gt;
&lt;li&gt;When the event occurred before the end of the study, the survival time is known.&lt;/li&gt;
&lt;li&gt;However, sometimes, the event is not yet observed at the end of the study. Suppose that we study the time until death of patients with breast cancer. Luckily, some patients will not die before the end of the study.
&lt;!-- + Other times, another event occurs before the event of interest which prevents it from ever happening. For example, a cancer patient may die from a car accident. --&gt;&lt;/li&gt;
&lt;li&gt;It can also happen that the patient withdraws from the study or moves to another country before the end of the study (known as lost to follow up or drop out).&lt;/li&gt;
&lt;li&gt;In all situations, his or her survival time cannot be observed because the event is not observed for the duration of the study.&lt;/li&gt;
&lt;li&gt;Censoring can be seen, in some sense, as a type of missing data.&lt;/li&gt;
&lt;li&gt;For these reasons, many “standard” statistical tools such as &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt;, &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt; and &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;regression models&lt;/a&gt; are not appropriate for this kind of data. Specific statistical methods are required to take into account the fact that the &lt;em&gt;exact&lt;/em&gt; survival duration for some patients is missing. It is known that they survived a certain amount of time (until the end of the study or until the time of withdrawal), but their exact survival time is unknown.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For your information, there are three types of censoring:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;right-censoring (the most frequent),&lt;/li&gt;
&lt;li&gt;left-censoring (the least frequent) and&lt;/li&gt;
&lt;li&gt;interval-censoring.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;When the event is not yet observed at the end of the study (i.e., the survival time is greater than the observed duration), this is referred as right-censoring. Left-censoring occurs if a participant is entered into the study when the event of interest occurred prior to study entry but we do not know exactly when. Interval-censoring implies that the event occurred within a time interval (between two known dates, two visits, etc.); the exact moment of occurrence is not known. The goal is of course to analyze all available data, including information about censored patients.&lt;/p&gt;
&lt;p&gt;The goal of survival analysis is thus to model and describe time-to-event data in an appropriate way, taking the particularities of this type of data into account.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;common-functions-in-survival-analysis&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Common functions in survival analysis&lt;/h1&gt;
&lt;p&gt;We are not going to go to much into the details, but it is important to lay the foundation with the most common functions in survival analysis.&lt;/p&gt;
&lt;p&gt;Let &lt;span class=&#34;math inline&#34;&gt;\(T\)&lt;/span&gt; be a non-negative continuous random variable, representing the time until the event of interest. We consider the following functions:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Survival function&lt;/li&gt;
&lt;li&gt;Cumulative hazard function&lt;/li&gt;
&lt;li&gt;Hazard function&lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&#34;survival-function&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Survival function&lt;/h2&gt;
&lt;p&gt;The most common one is the survival function.&lt;/p&gt;
&lt;p&gt;Let &lt;span class=&#34;math inline&#34;&gt;\(T\)&lt;/span&gt; be a non-negative continuous random variable, representing the time until the event of interest. The survival function &lt;span class=&#34;math inline&#34;&gt;\(S(t)\)&lt;/span&gt; is the probability that a randomly chosen individual is still at risk at time &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt;, where &lt;span class=&#34;math inline&#34;&gt;\(0 \le t \le +\infty\)&lt;/span&gt;. For each &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt;, it is given by&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
\begin{align*}
    S(t) &amp;amp;= P(T &amp;gt; t)\\
    &amp;amp;= 1 - P(T \le t)\\
    &amp;amp;= 1 - F(t)\\
    &amp;amp;= 1 - \int^t_0 f(u)\text{d}u,
\end{align*}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(f(\cdot)\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(F(\cdot)\)&lt;/span&gt; are the density and the cumulative distribution functions of &lt;span class=&#34;math inline&#34;&gt;\(T\)&lt;/span&gt;, respectively.&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(S(t)\)&lt;/span&gt; represents, for each time &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt;, the probability that the time until the event is greater than this time &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt;. In other words, it models the probability that the event of interest happens &lt;strong&gt;after&lt;/strong&gt; &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;In the context of our examples mentioned above, it gives the probability that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a randomly selected patient will survive beyond time &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt; or the proportion of patients still alive after time &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt;,&lt;/li&gt;
&lt;li&gt;a cab takes more than &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt; minutes to arrive, or&lt;/li&gt;
&lt;li&gt;an unemployed person take more than &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt; months to find a new job.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The survival function &lt;span class=&#34;math inline&#34;&gt;\(S(t)\)&lt;/span&gt; is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a decreasing function,&lt;/li&gt;
&lt;li&gt;taking values in &lt;span class=&#34;math inline&#34;&gt;\([0, 1]\)&lt;/span&gt; (since it is a probability), and&lt;/li&gt;
&lt;li&gt;equal to 1 at &lt;span class=&#34;math inline&#34;&gt;\(t = 0\)&lt;/span&gt; (i.e., &lt;span class=&#34;math inline&#34;&gt;\(S(0) = 1\)&lt;/span&gt;) and 0 at &lt;span class=&#34;math inline&#34;&gt;\(t = \infty\)&lt;/span&gt; (i.e., &lt;span class=&#34;math inline&#34;&gt;\(S(\infty) = 0\)&lt;/span&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Visually we have:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/what-is-survival-analysis/index_files/figure-html/unnamed-chunk-1-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The curve shows the proportion of individuals (or experimental units) who, as time goes on, have not experienced the event of interest. As time progresses, events occur, so the proportion who have not experienced the event decreases.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;cumulative-hazard-function&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Cumulative hazard function&lt;/h2&gt;
&lt;p&gt;The cumulative hazard function, which is the total hazard experienced up to time &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt;, is defined as:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[H(t) = -log\left(S(t)\right)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;and has the following properties:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;increasing function,&lt;/li&gt;
&lt;li&gt;taking value in &lt;span class=&#34;math inline&#34;&gt;\([0, +\infty]\)&lt;/span&gt;, and&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(S(t) = exp(-H(t))\)&lt;/span&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;hazard-function&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Hazard function&lt;/h2&gt;
&lt;p&gt;The hazard function &lt;span class=&#34;math inline&#34;&gt;\(h(t)\)&lt;/span&gt;, or hazard rate, defines the instantaneous event rate at time &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt; for an individual still at risk at that time. It can be obtained by&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
\begin{align*}
h(t) &amp;amp;= \lim_{\Delta t \rightarrow 0} \frac{P(t \le T &amp;lt; t + \Delta t | T \ge t)}{\Delta t}\\
&amp;amp;= \frac{d}{dt} H(t)\\
&amp;amp;= \frac{f(t)}{S(t)}.
\end{align*}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;and has the following properties:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;positive function (not necessarily increasing or decreasing)&lt;/li&gt;
&lt;li&gt;the hazard function &lt;span class=&#34;math inline&#34;&gt;\(h(t)\)&lt;/span&gt; can have many different shapes and is therefore a useful tool to summarize survival data&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In the context of cancer research when death is the event of interest, &lt;span class=&#34;math inline&#34;&gt;\(h(t)\)&lt;/span&gt; measures the instantaneous risk of dying right after time &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt; given the individual is alive at time &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;To link the hazard rate with the survival function; the survival curve represents the hazard rates. A steeper slope indicates a higher hazard rate because events happen more frequently, reducing the proportion of individuals who have not experienced the event at a faster rate. On the contrary, a gradual and flatter slope indicates a lower hazard rate because events occur less frequently, reducing the proportion of individuals who have not experiences the event at a slower rate. More formally:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[S(t) = \exp\left(-\int^t_0 h(u) \text{d}u\right).\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Note that, in contrast to the survival function which focuses on not having an event, the hazard function focuses on the event occurring.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;estimation&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Estimation&lt;/h1&gt;
&lt;p&gt;To estimate the survival function, we need to use an estimator which is able to deal with censoring. The most common one is the nonparametric &lt;strong&gt;&lt;span class=&#34;citation&#34;&gt;Kaplan and Meier (&lt;a href=&#34;#ref-kaplan1958nonparametric&#34;&gt;1958&lt;/a&gt;)&lt;/span&gt; estimator&lt;/strong&gt; (also sometimes referred as the product-limit estimator, or more simply, the K-M estimator).&lt;/p&gt;
&lt;p&gt;The advantages of the Kaplan-Meier estimator are that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;it is simple and straightforward to use and interpret&lt;/li&gt;
&lt;li&gt;it is a nonparametric estimator, so it constructs a survival curve from the data and no assumptions is made about the shape of the underlying distribution&lt;/li&gt;
&lt;li&gt;it gives a graphical representation of the survival function(s), useful for illustrative purposes&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The principle behind this estimator is that surviving beyond time &lt;span class=&#34;math inline&#34;&gt;\(t_i\)&lt;/span&gt; implies surviving beyond time &lt;span class=&#34;math inline&#34;&gt;\(t_{i-1}\)&lt;/span&gt; and surviving at time &lt;span class=&#34;math inline&#34;&gt;\(t_i\)&lt;/span&gt;. Note that an important assumption for the estimation to hold is that censoring is independent of the occurrence of events. We say that censoring is non-informative, that is, censored subjects have the same survival prospects as subjects who are not censored and who continue to be followed.&lt;/p&gt;
&lt;div id=&#34;by-hand&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;By hand&lt;/h2&gt;
&lt;p&gt;To understand how it works, let’s first estimate it by hand on the following dataset:&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;div id=&#34;ezedjhlbwf&#34; style=&#34;padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;&#34;&gt;
&lt;style&gt;#ezedjhlbwf table {
  font-family: system-ui, &#39;Segoe UI&#39;, Roboto, Helvetica, Arial, sans-serif, &#39;Apple Color Emoji&#39;, &#39;Segoe UI Emoji&#39;, &#39;Segoe UI Symbol&#39;, &#39;Noto Color Emoji&#39;;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

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

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

#ezedjhlbwf .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;
}

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

#ezedjhlbwf .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;
}

#ezedjhlbwf .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;
}

#ezedjhlbwf .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;
}

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

#ezedjhlbwf .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;
}

#ezedjhlbwf .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;
}

#ezedjhlbwf .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;
}

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

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

#ezedjhlbwf .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%;
}

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

#ezedjhlbwf .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;
}

#ezedjhlbwf .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;
}

#ezedjhlbwf .gt_from_md &gt; :first-child {
  margin-top: 0;
}

#ezedjhlbwf .gt_from_md &gt; :last-child {
  margin-bottom: 0;
}

#ezedjhlbwf .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;
}

#ezedjhlbwf .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;
}

#ezedjhlbwf .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;
}

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

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

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

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

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

#ezedjhlbwf .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;
}

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

#ezedjhlbwf .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;
}

#ezedjhlbwf .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;
}

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

#ezedjhlbwf .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;
}

#ezedjhlbwf .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;
}

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

#ezedjhlbwf .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;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#ezedjhlbwf div.Reactable &gt; div.rt-table &gt; div.rt-thead &gt; div.rt-tr.rt-tr-group-header &gt; div.rt-th-group:after {
  height: 0px !important;
}
&lt;/style&gt;
&lt;table class=&#34;gt_table&#34; data-quarto-disable-processing=&#34;false&#34; data-quarto-bootstrap=&#34;false&#34;&gt;
  &lt;thead&gt;
    &lt;tr class=&#34;gt_col_headings&#34;&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;subject&#34;&gt;subject&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;time&#34;&gt;time&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_right&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;event&#34;&gt;event&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody class=&#34;gt_table_body&#34;&gt;
    &lt;tr&gt;&lt;td headers=&#34;subject&#34; class=&#34;gt_row gt_right&#34;&gt;1&lt;/td&gt;
&lt;td headers=&#34;time&#34; class=&#34;gt_row gt_right&#34;&gt;3&lt;/td&gt;
&lt;td headers=&#34;event&#34; class=&#34;gt_row gt_right&#34;&gt;0&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;subject&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;
&lt;td headers=&#34;time&#34; class=&#34;gt_row gt_right&#34;&gt;5&lt;/td&gt;
&lt;td headers=&#34;event&#34; class=&#34;gt_row gt_right&#34;&gt;1&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;subject&#34; class=&#34;gt_row gt_right&#34;&gt;3&lt;/td&gt;
&lt;td headers=&#34;time&#34; class=&#34;gt_row gt_right&#34;&gt;7&lt;/td&gt;
&lt;td headers=&#34;event&#34; class=&#34;gt_row gt_right&#34;&gt;1&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;subject&#34; class=&#34;gt_row gt_right&#34;&gt;4&lt;/td&gt;
&lt;td headers=&#34;time&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;
&lt;td headers=&#34;event&#34; class=&#34;gt_row gt_right&#34;&gt;1&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;subject&#34; class=&#34;gt_row gt_right&#34;&gt;5&lt;/td&gt;
&lt;td headers=&#34;time&#34; class=&#34;gt_row gt_right&#34;&gt;18&lt;/td&gt;
&lt;td headers=&#34;event&#34; class=&#34;gt_row gt_right&#34;&gt;0&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;subject&#34; class=&#34;gt_row gt_right&#34;&gt;6&lt;/td&gt;
&lt;td headers=&#34;time&#34; class=&#34;gt_row gt_right&#34;&gt;16&lt;/td&gt;
&lt;td headers=&#34;event&#34; class=&#34;gt_row gt_right&#34;&gt;1&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;subject&#34; class=&#34;gt_row gt_right&#34;&gt;7&lt;/td&gt;
&lt;td headers=&#34;time&#34; class=&#34;gt_row gt_right&#34;&gt;2&lt;/td&gt;
&lt;td headers=&#34;event&#34; class=&#34;gt_row gt_right&#34;&gt;1&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;subject&#34; class=&#34;gt_row gt_right&#34;&gt;8&lt;/td&gt;
&lt;td headers=&#34;time&#34; class=&#34;gt_row gt_right&#34;&gt;9&lt;/td&gt;
&lt;td headers=&#34;event&#34; class=&#34;gt_row gt_right&#34;&gt;1&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;subject&#34; class=&#34;gt_row gt_right&#34;&gt;9&lt;/td&gt;
&lt;td headers=&#34;time&#34; class=&#34;gt_row gt_right&#34;&gt;16&lt;/td&gt;
&lt;td headers=&#34;event&#34; class=&#34;gt_row gt_right&#34;&gt;1&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;subject&#34; class=&#34;gt_row gt_right&#34;&gt;10&lt;/td&gt;
&lt;td headers=&#34;time&#34; class=&#34;gt_row gt_right&#34;&gt;5&lt;/td&gt;
&lt;td headers=&#34;event&#34; class=&#34;gt_row gt_right&#34;&gt;0&lt;/td&gt;&lt;/tr&gt;
  &lt;/tbody&gt;
  
&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;subject&lt;/code&gt; is the individual’s identifier&lt;/li&gt;
&lt;li&gt;&lt;code&gt;time&lt;/code&gt; is the time to event (in years)&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;event&lt;/code&gt; is the event status (0 = censored, 1 = event happened)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Remember that for each subject, we need to know at least 2 pieces of information:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;the time until the event of interest or the time until the censoring, and&lt;/li&gt;
&lt;li&gt;whether we have observed the event of interest or if we have observed censoring.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;We first need to count the number of distinct event times. Ignoring censored observations, we have 5 distinct event times:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;2&lt;/em&gt;, &lt;em&gt;5&lt;/em&gt;, &lt;em&gt;7&lt;/em&gt;, &lt;em&gt;9&lt;/em&gt; and &lt;em&gt;16&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The easiest way to do the calculation by hand is by filling the following table (a table with 5 rows since there are 5 distinct event times):&lt;/p&gt;
&lt;!-- preamble start --&gt;

    &lt;script src=&#34;https://cdn.jsdelivr.net/gh/vincentarelbundock/tinytable@main/inst/tinytable.js&#34;&gt;&lt;/script&gt;

    &lt;script&gt;
      // Create table-specific functions using external factory
      const tableFns_gqi6wniv912vuheaxhyt = TinyTable.createTableFunctions(&#34;tinytable_gqi6wniv912vuheaxhyt&#34;);
      // tinytable span after
      window.addEventListener(&#39;load&#39;, function () {
          var cellsToStyle = [
            // tinytable style arrays after
          { positions: [ { i: &#39;5&#39;, j: 1 }, { i: &#39;5&#39;, j: 2 }, { i: &#39;5&#39;, j: 3 }, { i: &#39;5&#39;, j: 4 }, { i: &#39;5&#39;, j: 5 } ], css_id: &#39;tinytable_css_63tzhumrxmy06nvag0kk&#39;,}, 
          { positions: [ { i: &#39;1&#39;, j: 1 }, { i: &#39;2&#39;, j: 1 }, { i: &#39;3&#39;, j: 1 }, { i: &#39;4&#39;, j: 1 }, { i: &#39;1&#39;, j: 2 }, { i: &#39;2&#39;, j: 2 }, { i: &#39;3&#39;, j: 2 }, { i: &#39;4&#39;, j: 2 }, { i: &#39;1&#39;, j: 3 }, { i: &#39;2&#39;, j: 3 }, { i: &#39;3&#39;, j: 3 }, { i: &#39;4&#39;, j: 3 }, { i: &#39;1&#39;, j: 4 }, { i: &#39;2&#39;, j: 4 }, { i: &#39;3&#39;, j: 4 }, { i: &#39;4&#39;, j: 4 }, { i: &#39;1&#39;, j: 5 }, { i: &#39;2&#39;, j: 5 }, { i: &#39;3&#39;, j: 5 }, { i: &#39;4&#39;, j: 5 } ], css_id: &#39;tinytable_css_odk2y8mjqugbkfu3h9e3&#39;,}, 
          { positions: [ { i: &#39;0&#39;, j: 1 }, { i: &#39;0&#39;, j: 2 }, { i: &#39;0&#39;, j: 3 }, { i: &#39;0&#39;, j: 4 }, { i: &#39;0&#39;, j: 5 } ], css_id: &#39;tinytable_css_x7q8xsf3ainkuuago1c3&#39;,}, 
          ];

          // Loop over the arrays to style the cells
          cellsToStyle.forEach(function (group) {
              group.positions.forEach(function (cell) {
                  tableFns_gqi6wniv912vuheaxhyt.styleCell(cell.i, cell.j, group.css_id);
              });
          });
      });
    &lt;/script&gt;

    &lt;link rel=&#34;stylesheet&#34; href=&#34;https://cdn.jsdelivr.net/gh/vincentarelbundock/tinytable@main/inst/tinytable.css&#34;&gt;
    &lt;style&gt;
    /* tinytable css entries after */
    #tinytable_gqi6wniv912vuheaxhyt td.tinytable_css_63tzhumrxmy06nvag0kk, #tinytable_gqi6wniv912vuheaxhyt th.tinytable_css_63tzhumrxmy06nvag0kk {  position: relative; --border-bottom: 1; --border-left: 0; --border-right: 0; --border-top: 0; --line-color-bottom: var(--tt-line-color); --line-color-left: var(--tt-line-color); --line-color-right: var(--tt-line-color); --line-color-top: var(--tt-line-color); --line-width-bottom: 0.08em; --line-width-left: 0.1em; --line-width-right: 0.1em; --line-width-top: 0.1em; --trim-bottom-left: 0%; --trim-bottom-right: 0%; --trim-left-bottom: 0%; --trim-left-top: 0%; --trim-right-bottom: 0%; --trim-right-top: 0%; --trim-top-left: 0%; --trim-top-right: 0%; ; text-align: left }
    #tinytable_gqi6wniv912vuheaxhyt td.tinytable_css_odk2y8mjqugbkfu3h9e3, #tinytable_gqi6wniv912vuheaxhyt th.tinytable_css_odk2y8mjqugbkfu3h9e3 { text-align: left }
    #tinytable_gqi6wniv912vuheaxhyt td.tinytable_css_x7q8xsf3ainkuuago1c3, #tinytable_gqi6wniv912vuheaxhyt th.tinytable_css_x7q8xsf3ainkuuago1c3 {  position: relative; --border-bottom: 1; --border-left: 0; --border-right: 0; --border-top: 1; --line-color-bottom: var(--tt-line-color); --line-color-left: var(--tt-line-color); --line-color-right: var(--tt-line-color); --line-color-top: var(--tt-line-color); --line-width-bottom: 0.05em; --line-width-left: 0.1em; --line-width-right: 0.1em; --line-width-top: 0.08em; --trim-bottom-left: 0%; --trim-bottom-right: 0%; --trim-left-bottom: 0%; --trim-left-top: 0%; --trim-right-bottom: 0%; --trim-right-top: 0%; --trim-top-left: 0%; --trim-top-right: 0%; ; text-align: left }
    &lt;/style&gt;
    &lt;div class=&#34;container&#34;&gt;
      &lt;table class=&#34;tinytable&#34; id=&#34;tinytable_gqi6wniv912vuheaxhyt&#34; style=&#34;width: auto; margin-left: auto; margin-right: auto;&#34; data-quarto-disable-processing=&#39;true&#39;&gt;
        
        &lt;thead&gt;
              &lt;tr&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;1&#34;&gt;$j$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;2&#34;&gt;$y_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;3&#34;&gt;$d_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;4&#34;&gt;$R_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;5&#34;&gt;$1 - \frac{d_{(j)}}{R_{(j)}}$&lt;/th&gt;
              &lt;/tr&gt;
        &lt;/thead&gt;
        
        &lt;tbody&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;1&#34;&gt;1&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;2&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;3&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;1&#34;&gt;2&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;2&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;3&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;1&#34;&gt;3&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;2&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;3&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;1&#34;&gt;4&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;2&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;3&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;1&#34;&gt;5&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;2&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;3&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;
&lt;!-- hack to avoid NA insertion in last line --&gt;
&lt;p&gt;We fill columns one by one:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(y_{(j)}\)&lt;/span&gt; = the ordered distinct event times:&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;2&lt;/em&gt;, &lt;em&gt;5&lt;/em&gt;, &lt;em&gt;7&lt;/em&gt;, &lt;em&gt;9&lt;/em&gt; and &lt;em&gt;16&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;So the table becomes:&lt;/p&gt;
&lt;!-- preamble start --&gt;

    &lt;script src=&#34;https://cdn.jsdelivr.net/gh/vincentarelbundock/tinytable@main/inst/tinytable.js&#34;&gt;&lt;/script&gt;

    &lt;script&gt;
      // Create table-specific functions using external factory
      const tableFns_pfttpztdnahkfolt80rf = TinyTable.createTableFunctions(&#34;tinytable_pfttpztdnahkfolt80rf&#34;);
      // tinytable span after
      window.addEventListener(&#39;load&#39;, function () {
          var cellsToStyle = [
            // tinytable style arrays after
          { positions: [ { i: &#39;5&#39;, j: 1 }, { i: &#39;5&#39;, j: 2 }, { i: &#39;5&#39;, j: 3 }, { i: &#39;5&#39;, j: 4 }, { i: &#39;5&#39;, j: 5 } ], css_id: &#39;tinytable_css_6a61u2qsubu2inwtd56y&#39;,}, 
          { positions: [ { i: &#39;1&#39;, j: 1 }, { i: &#39;2&#39;, j: 1 }, { i: &#39;3&#39;, j: 1 }, { i: &#39;4&#39;, j: 1 }, { i: &#39;1&#39;, j: 2 }, { i: &#39;2&#39;, j: 2 }, { i: &#39;3&#39;, j: 2 }, { i: &#39;4&#39;, j: 2 }, { i: &#39;1&#39;, j: 3 }, { i: &#39;2&#39;, j: 3 }, { i: &#39;3&#39;, j: 3 }, { i: &#39;4&#39;, j: 3 }, { i: &#39;1&#39;, j: 4 }, { i: &#39;2&#39;, j: 4 }, { i: &#39;3&#39;, j: 4 }, { i: &#39;4&#39;, j: 4 }, { i: &#39;1&#39;, j: 5 }, { i: &#39;2&#39;, j: 5 }, { i: &#39;3&#39;, j: 5 }, { i: &#39;4&#39;, j: 5 } ], css_id: &#39;tinytable_css_8lne9bdpjx6dn6p4x3gd&#39;,}, 
          { positions: [ { i: &#39;0&#39;, j: 1 }, { i: &#39;0&#39;, j: 2 }, { i: &#39;0&#39;, j: 3 }, { i: &#39;0&#39;, j: 4 }, { i: &#39;0&#39;, j: 5 } ], css_id: &#39;tinytable_css_bniz86tc4lp4m19bq9xc&#39;,}, 
          ];

          // Loop over the arrays to style the cells
          cellsToStyle.forEach(function (group) {
              group.positions.forEach(function (cell) {
                  tableFns_pfttpztdnahkfolt80rf.styleCell(cell.i, cell.j, group.css_id);
              });
          });
      });
    &lt;/script&gt;

    &lt;link rel=&#34;stylesheet&#34; href=&#34;https://cdn.jsdelivr.net/gh/vincentarelbundock/tinytable@main/inst/tinytable.css&#34;&gt;
    &lt;style&gt;
    /* tinytable css entries after */
    #tinytable_pfttpztdnahkfolt80rf td.tinytable_css_6a61u2qsubu2inwtd56y, #tinytable_pfttpztdnahkfolt80rf th.tinytable_css_6a61u2qsubu2inwtd56y {  position: relative; --border-bottom: 1; --border-left: 0; --border-right: 0; --border-top: 0; --line-color-bottom: var(--tt-line-color); --line-color-left: var(--tt-line-color); --line-color-right: var(--tt-line-color); --line-color-top: var(--tt-line-color); --line-width-bottom: 0.08em; --line-width-left: 0.1em; --line-width-right: 0.1em; --line-width-top: 0.1em; --trim-bottom-left: 0%; --trim-bottom-right: 0%; --trim-left-bottom: 0%; --trim-left-top: 0%; --trim-right-bottom: 0%; --trim-right-top: 0%; --trim-top-left: 0%; --trim-top-right: 0%; ; text-align: left }
    #tinytable_pfttpztdnahkfolt80rf td.tinytable_css_8lne9bdpjx6dn6p4x3gd, #tinytable_pfttpztdnahkfolt80rf th.tinytable_css_8lne9bdpjx6dn6p4x3gd { text-align: left }
    #tinytable_pfttpztdnahkfolt80rf td.tinytable_css_bniz86tc4lp4m19bq9xc, #tinytable_pfttpztdnahkfolt80rf th.tinytable_css_bniz86tc4lp4m19bq9xc {  position: relative; --border-bottom: 1; --border-left: 0; --border-right: 0; --border-top: 1; --line-color-bottom: var(--tt-line-color); --line-color-left: var(--tt-line-color); --line-color-right: var(--tt-line-color); --line-color-top: var(--tt-line-color); --line-width-bottom: 0.05em; --line-width-left: 0.1em; --line-width-right: 0.1em; --line-width-top: 0.08em; --trim-bottom-left: 0%; --trim-bottom-right: 0%; --trim-left-bottom: 0%; --trim-left-top: 0%; --trim-right-bottom: 0%; --trim-right-top: 0%; --trim-top-left: 0%; --trim-top-right: 0%; ; text-align: left }
    &lt;/style&gt;
    &lt;div class=&#34;container&#34;&gt;
      &lt;table class=&#34;tinytable&#34; id=&#34;tinytable_pfttpztdnahkfolt80rf&#34; style=&#34;width: auto; margin-left: auto; margin-right: auto;&#34; data-quarto-disable-processing=&#39;true&#39;&gt;
        
        &lt;thead&gt;
              &lt;tr&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;1&#34;&gt;$j$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;2&#34;&gt;$y_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;3&#34;&gt;$d_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;4&#34;&gt;$R_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;5&#34;&gt;$1 - \frac{d_{(j)}}{R_{(j)}}$&lt;/th&gt;
              &lt;/tr&gt;
        &lt;/thead&gt;
        
        &lt;tbody&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;1&#34;&gt;1&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;2&#34;&gt;2&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;3&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;1&#34;&gt;2&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;2&#34;&gt;5&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;3&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;1&#34;&gt;3&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;2&#34;&gt;7&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;3&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;1&#34;&gt;4&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;2&#34;&gt;9&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;3&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;1&#34;&gt;5&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;2&#34;&gt;16&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;3&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;
&lt;!-- hack to avoid NA insertion in last line --&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(d_{(j)}\)&lt;/span&gt; = the number of observations for each distinct event time. For this, the frequency for each distinct event time is useful:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;## time
##  2  5  7  9 16 
##  2  1  1  1  2&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The table becomes:&lt;/p&gt;
&lt;!-- preamble start --&gt;

    &lt;script src=&#34;https://cdn.jsdelivr.net/gh/vincentarelbundock/tinytable@main/inst/tinytable.js&#34;&gt;&lt;/script&gt;

    &lt;script&gt;
      // Create table-specific functions using external factory
      const tableFns_jyqpf16iauwvmx2i0oim = TinyTable.createTableFunctions(&#34;tinytable_jyqpf16iauwvmx2i0oim&#34;);
      // tinytable span after
      window.addEventListener(&#39;load&#39;, function () {
          var cellsToStyle = [
            // tinytable style arrays after
          { positions: [ { i: &#39;5&#39;, j: 1 }, { i: &#39;5&#39;, j: 2 }, { i: &#39;5&#39;, j: 3 }, { i: &#39;5&#39;, j: 4 }, { i: &#39;5&#39;, j: 5 } ], css_id: &#39;tinytable_css_p57hqjnq2thdknhk1o3h&#39;,}, 
          { positions: [ { i: &#39;1&#39;, j: 1 }, { i: &#39;2&#39;, j: 1 }, { i: &#39;3&#39;, j: 1 }, { i: &#39;4&#39;, j: 1 }, { i: &#39;1&#39;, j: 2 }, { i: &#39;2&#39;, j: 2 }, { i: &#39;3&#39;, j: 2 }, { i: &#39;4&#39;, j: 2 }, { i: &#39;1&#39;, j: 3 }, { i: &#39;2&#39;, j: 3 }, { i: &#39;3&#39;, j: 3 }, { i: &#39;4&#39;, j: 3 }, { i: &#39;1&#39;, j: 4 }, { i: &#39;2&#39;, j: 4 }, { i: &#39;3&#39;, j: 4 }, { i: &#39;4&#39;, j: 4 }, { i: &#39;1&#39;, j: 5 }, { i: &#39;2&#39;, j: 5 }, { i: &#39;3&#39;, j: 5 }, { i: &#39;4&#39;, j: 5 } ], css_id: &#39;tinytable_css_uci8h8g7nt7wfi557l1d&#39;,}, 
          { positions: [ { i: &#39;0&#39;, j: 1 }, { i: &#39;0&#39;, j: 2 }, { i: &#39;0&#39;, j: 3 }, { i: &#39;0&#39;, j: 4 }, { i: &#39;0&#39;, j: 5 } ], css_id: &#39;tinytable_css_689d9x9gs8twi4f8vbpv&#39;,}, 
          ];

          // Loop over the arrays to style the cells
          cellsToStyle.forEach(function (group) {
              group.positions.forEach(function (cell) {
                  tableFns_jyqpf16iauwvmx2i0oim.styleCell(cell.i, cell.j, group.css_id);
              });
          });
      });
    &lt;/script&gt;

    &lt;link rel=&#34;stylesheet&#34; href=&#34;https://cdn.jsdelivr.net/gh/vincentarelbundock/tinytable@main/inst/tinytable.css&#34;&gt;
    &lt;style&gt;
    /* tinytable css entries after */
    #tinytable_jyqpf16iauwvmx2i0oim td.tinytable_css_p57hqjnq2thdknhk1o3h, #tinytable_jyqpf16iauwvmx2i0oim th.tinytable_css_p57hqjnq2thdknhk1o3h {  position: relative; --border-bottom: 1; --border-left: 0; --border-right: 0; --border-top: 0; --line-color-bottom: var(--tt-line-color); --line-color-left: var(--tt-line-color); --line-color-right: var(--tt-line-color); --line-color-top: var(--tt-line-color); --line-width-bottom: 0.08em; --line-width-left: 0.1em; --line-width-right: 0.1em; --line-width-top: 0.1em; --trim-bottom-left: 0%; --trim-bottom-right: 0%; --trim-left-bottom: 0%; --trim-left-top: 0%; --trim-right-bottom: 0%; --trim-right-top: 0%; --trim-top-left: 0%; --trim-top-right: 0%; ; text-align: left }
    #tinytable_jyqpf16iauwvmx2i0oim td.tinytable_css_uci8h8g7nt7wfi557l1d, #tinytable_jyqpf16iauwvmx2i0oim th.tinytable_css_uci8h8g7nt7wfi557l1d { text-align: left }
    #tinytable_jyqpf16iauwvmx2i0oim td.tinytable_css_689d9x9gs8twi4f8vbpv, #tinytable_jyqpf16iauwvmx2i0oim th.tinytable_css_689d9x9gs8twi4f8vbpv {  position: relative; --border-bottom: 1; --border-left: 0; --border-right: 0; --border-top: 1; --line-color-bottom: var(--tt-line-color); --line-color-left: var(--tt-line-color); --line-color-right: var(--tt-line-color); --line-color-top: var(--tt-line-color); --line-width-bottom: 0.05em; --line-width-left: 0.1em; --line-width-right: 0.1em; --line-width-top: 0.08em; --trim-bottom-left: 0%; --trim-bottom-right: 0%; --trim-left-bottom: 0%; --trim-left-top: 0%; --trim-right-bottom: 0%; --trim-right-top: 0%; --trim-top-left: 0%; --trim-top-right: 0%; ; text-align: left }
    &lt;/style&gt;
    &lt;div class=&#34;container&#34;&gt;
      &lt;table class=&#34;tinytable&#34; id=&#34;tinytable_jyqpf16iauwvmx2i0oim&#34; style=&#34;width: auto; margin-left: auto; margin-right: auto;&#34; data-quarto-disable-processing=&#39;true&#39;&gt;
        
        &lt;thead&gt;
              &lt;tr&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;1&#34;&gt;$j$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;2&#34;&gt;$y_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;3&#34;&gt;$d_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;4&#34;&gt;$R_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;5&#34;&gt;$1 - \frac{d_{(j)}}{R_{(j)}}$&lt;/th&gt;
              &lt;/tr&gt;
        &lt;/thead&gt;
        
        &lt;tbody&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;1&#34;&gt;1&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;2&#34;&gt;2&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;3&#34;&gt;2&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;1&#34;&gt;2&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;2&#34;&gt;5&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;3&#34;&gt;1&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;1&#34;&gt;3&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;2&#34;&gt;7&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;3&#34;&gt;1&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;1&#34;&gt;4&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;2&#34;&gt;9&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;3&#34;&gt;1&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;1&#34;&gt;5&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;2&#34;&gt;16&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;3&#34;&gt;2&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;4&#34;&gt;&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;
&lt;!-- hack to avoid NA insertion in last line --&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(R_{(j)}\)&lt;/span&gt; = the remaining number of individuals at risk. For this, the distribution of time (censored and not censored) is useful:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;## time
##  2  3  5  7  9 16 18 
##  2  1  2  1  1  2  1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We see that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;At the beginning there are 10 subjects&lt;/li&gt;
&lt;li&gt;Just before time &lt;span class=&#34;math inline&#34;&gt;\(t = 5\)&lt;/span&gt;, there are 7 subjects left (10 subjects - 2 who had the event - 1 who is censored)&lt;/li&gt;
&lt;li&gt;Just before time &lt;span class=&#34;math inline&#34;&gt;\(t = 7\)&lt;/span&gt;, there are 5 subjects left (= 10 - 2 - 1 - 2)&lt;/li&gt;
&lt;li&gt;Just before time &lt;span class=&#34;math inline&#34;&gt;\(t = 9\)&lt;/span&gt;, there are 4 subjects left (= 10 - 2 - 1 - 2 - 1)&lt;/li&gt;
&lt;li&gt;Just before time &lt;span class=&#34;math inline&#34;&gt;\(t = 16\)&lt;/span&gt;, there are 3 subjects left (= 10 - 2 - 1 - 2 - 1 - 1)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The table becomes:&lt;/p&gt;
&lt;!-- preamble start --&gt;

    &lt;script src=&#34;https://cdn.jsdelivr.net/gh/vincentarelbundock/tinytable@main/inst/tinytable.js&#34;&gt;&lt;/script&gt;

    &lt;script&gt;
      // Create table-specific functions using external factory
      const tableFns_13fjo3fhqofxmr77b0ro = TinyTable.createTableFunctions(&#34;tinytable_13fjo3fhqofxmr77b0ro&#34;);
      // tinytable span after
      window.addEventListener(&#39;load&#39;, function () {
          var cellsToStyle = [
            // tinytable style arrays after
          { positions: [ { i: &#39;5&#39;, j: 1 }, { i: &#39;5&#39;, j: 2 }, { i: &#39;5&#39;, j: 3 }, { i: &#39;5&#39;, j: 4 }, { i: &#39;5&#39;, j: 5 } ], css_id: &#39;tinytable_css_05oab03bspdqdzznbf9c&#39;,}, 
          { positions: [ { i: &#39;1&#39;, j: 1 }, { i: &#39;2&#39;, j: 1 }, { i: &#39;3&#39;, j: 1 }, { i: &#39;4&#39;, j: 1 }, { i: &#39;1&#39;, j: 2 }, { i: &#39;2&#39;, j: 2 }, { i: &#39;3&#39;, j: 2 }, { i: &#39;4&#39;, j: 2 }, { i: &#39;1&#39;, j: 3 }, { i: &#39;2&#39;, j: 3 }, { i: &#39;3&#39;, j: 3 }, { i: &#39;4&#39;, j: 3 }, { i: &#39;1&#39;, j: 4 }, { i: &#39;2&#39;, j: 4 }, { i: &#39;3&#39;, j: 4 }, { i: &#39;4&#39;, j: 4 }, { i: &#39;1&#39;, j: 5 }, { i: &#39;2&#39;, j: 5 }, { i: &#39;3&#39;, j: 5 }, { i: &#39;4&#39;, j: 5 } ], css_id: &#39;tinytable_css_h96li1wtavwkgoy72cy6&#39;,}, 
          { positions: [ { i: &#39;0&#39;, j: 1 }, { i: &#39;0&#39;, j: 2 }, { i: &#39;0&#39;, j: 3 }, { i: &#39;0&#39;, j: 4 }, { i: &#39;0&#39;, j: 5 } ], css_id: &#39;tinytable_css_cb86r59qgslap7na03m7&#39;,}, 
          ];

          // Loop over the arrays to style the cells
          cellsToStyle.forEach(function (group) {
              group.positions.forEach(function (cell) {
                  tableFns_13fjo3fhqofxmr77b0ro.styleCell(cell.i, cell.j, group.css_id);
              });
          });
      });
    &lt;/script&gt;

    &lt;link rel=&#34;stylesheet&#34; href=&#34;https://cdn.jsdelivr.net/gh/vincentarelbundock/tinytable@main/inst/tinytable.css&#34;&gt;
    &lt;style&gt;
    /* tinytable css entries after */
    #tinytable_13fjo3fhqofxmr77b0ro td.tinytable_css_05oab03bspdqdzznbf9c, #tinytable_13fjo3fhqofxmr77b0ro th.tinytable_css_05oab03bspdqdzznbf9c {  position: relative; --border-bottom: 1; --border-left: 0; --border-right: 0; --border-top: 0; --line-color-bottom: var(--tt-line-color); --line-color-left: var(--tt-line-color); --line-color-right: var(--tt-line-color); --line-color-top: var(--tt-line-color); --line-width-bottom: 0.08em; --line-width-left: 0.1em; --line-width-right: 0.1em; --line-width-top: 0.1em; --trim-bottom-left: 0%; --trim-bottom-right: 0%; --trim-left-bottom: 0%; --trim-left-top: 0%; --trim-right-bottom: 0%; --trim-right-top: 0%; --trim-top-left: 0%; --trim-top-right: 0%; ; text-align: left }
    #tinytable_13fjo3fhqofxmr77b0ro td.tinytable_css_h96li1wtavwkgoy72cy6, #tinytable_13fjo3fhqofxmr77b0ro th.tinytable_css_h96li1wtavwkgoy72cy6 { text-align: left }
    #tinytable_13fjo3fhqofxmr77b0ro td.tinytable_css_cb86r59qgslap7na03m7, #tinytable_13fjo3fhqofxmr77b0ro th.tinytable_css_cb86r59qgslap7na03m7 {  position: relative; --border-bottom: 1; --border-left: 0; --border-right: 0; --border-top: 1; --line-color-bottom: var(--tt-line-color); --line-color-left: var(--tt-line-color); --line-color-right: var(--tt-line-color); --line-color-top: var(--tt-line-color); --line-width-bottom: 0.05em; --line-width-left: 0.1em; --line-width-right: 0.1em; --line-width-top: 0.08em; --trim-bottom-left: 0%; --trim-bottom-right: 0%; --trim-left-bottom: 0%; --trim-left-top: 0%; --trim-right-bottom: 0%; --trim-right-top: 0%; --trim-top-left: 0%; --trim-top-right: 0%; ; text-align: left }
    &lt;/style&gt;
    &lt;div class=&#34;container&#34;&gt;
      &lt;table class=&#34;tinytable&#34; id=&#34;tinytable_13fjo3fhqofxmr77b0ro&#34; style=&#34;width: auto; margin-left: auto; margin-right: auto;&#34; data-quarto-disable-processing=&#39;true&#39;&gt;
        
        &lt;thead&gt;
              &lt;tr&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;1&#34;&gt;$j$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;2&#34;&gt;$y_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;3&#34;&gt;$d_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;4&#34;&gt;$R_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;5&#34;&gt;$1 - \frac{d_{(j)}}{R_{(j)}}$&lt;/th&gt;
              &lt;/tr&gt;
        &lt;/thead&gt;
        
        &lt;tbody&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;1&#34;&gt;1&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;2&#34;&gt;2&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;3&#34;&gt;2&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;4&#34;&gt;10&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;1&#34;&gt;2&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;2&#34;&gt;5&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;3&#34;&gt;1&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;4&#34;&gt;7&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;1&#34;&gt;3&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;2&#34;&gt;7&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;3&#34;&gt;1&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;4&#34;&gt;5&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;1&#34;&gt;4&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;2&#34;&gt;9&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;3&#34;&gt;1&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;4&#34;&gt;4&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;1&#34;&gt;5&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;2&#34;&gt;16&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;3&#34;&gt;2&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;4&#34;&gt;3&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;5&#34;&gt;&lt;/td&gt;
                &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;
&lt;!-- hack to avoid NA insertion in last line --&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(1 - \frac{d_{(j)}}{R_{(j)}}\)&lt;/span&gt; is straightforward, so the table becomes:&lt;/li&gt;
&lt;/ul&gt;
&lt;!-- preamble start --&gt;

    &lt;script src=&#34;https://cdn.jsdelivr.net/gh/vincentarelbundock/tinytable@main/inst/tinytable.js&#34;&gt;&lt;/script&gt;

    &lt;script&gt;
      // Create table-specific functions using external factory
      const tableFns_pwro8an6lcdmghyyn84k = TinyTable.createTableFunctions(&#34;tinytable_pwro8an6lcdmghyyn84k&#34;);
      // tinytable span after
      window.addEventListener(&#39;load&#39;, function () {
          var cellsToStyle = [
            // tinytable style arrays after
          { positions: [ { i: &#39;5&#39;, j: 1 }, { i: &#39;5&#39;, j: 2 }, { i: &#39;5&#39;, j: 3 }, { i: &#39;5&#39;, j: 4 }, { i: &#39;5&#39;, j: 5 } ], css_id: &#39;tinytable_css_kvroag0647on9aibrtmk&#39;,}, 
          { positions: [ { i: &#39;1&#39;, j: 1 }, { i: &#39;2&#39;, j: 1 }, { i: &#39;3&#39;, j: 1 }, { i: &#39;4&#39;, j: 1 }, { i: &#39;1&#39;, j: 2 }, { i: &#39;2&#39;, j: 2 }, { i: &#39;3&#39;, j: 2 }, { i: &#39;4&#39;, j: 2 }, { i: &#39;1&#39;, j: 3 }, { i: &#39;2&#39;, j: 3 }, { i: &#39;3&#39;, j: 3 }, { i: &#39;4&#39;, j: 3 }, { i: &#39;1&#39;, j: 4 }, { i: &#39;2&#39;, j: 4 }, { i: &#39;3&#39;, j: 4 }, { i: &#39;4&#39;, j: 4 }, { i: &#39;1&#39;, j: 5 }, { i: &#39;2&#39;, j: 5 }, { i: &#39;3&#39;, j: 5 }, { i: &#39;4&#39;, j: 5 } ], css_id: &#39;tinytable_css_jdhilsydd0ovjj4g5zxc&#39;,}, 
          { positions: [ { i: &#39;0&#39;, j: 1 }, { i: &#39;0&#39;, j: 2 }, { i: &#39;0&#39;, j: 3 }, { i: &#39;0&#39;, j: 4 }, { i: &#39;0&#39;, j: 5 } ], css_id: &#39;tinytable_css_2l0ch1qqpad19ftfdsmj&#39;,}, 
          ];

          // Loop over the arrays to style the cells
          cellsToStyle.forEach(function (group) {
              group.positions.forEach(function (cell) {
                  tableFns_pwro8an6lcdmghyyn84k.styleCell(cell.i, cell.j, group.css_id);
              });
          });
      });
    &lt;/script&gt;

    &lt;link rel=&#34;stylesheet&#34; href=&#34;https://cdn.jsdelivr.net/gh/vincentarelbundock/tinytable@main/inst/tinytable.css&#34;&gt;
    &lt;style&gt;
    /* tinytable css entries after */
    #tinytable_pwro8an6lcdmghyyn84k td.tinytable_css_kvroag0647on9aibrtmk, #tinytable_pwro8an6lcdmghyyn84k th.tinytable_css_kvroag0647on9aibrtmk {  position: relative; --border-bottom: 1; --border-left: 0; --border-right: 0; --border-top: 0; --line-color-bottom: var(--tt-line-color); --line-color-left: var(--tt-line-color); --line-color-right: var(--tt-line-color); --line-color-top: var(--tt-line-color); --line-width-bottom: 0.08em; --line-width-left: 0.1em; --line-width-right: 0.1em; --line-width-top: 0.1em; --trim-bottom-left: 0%; --trim-bottom-right: 0%; --trim-left-bottom: 0%; --trim-left-top: 0%; --trim-right-bottom: 0%; --trim-right-top: 0%; --trim-top-left: 0%; --trim-top-right: 0%; ; text-align: left }
    #tinytable_pwro8an6lcdmghyyn84k td.tinytable_css_jdhilsydd0ovjj4g5zxc, #tinytable_pwro8an6lcdmghyyn84k th.tinytable_css_jdhilsydd0ovjj4g5zxc { text-align: left }
    #tinytable_pwro8an6lcdmghyyn84k td.tinytable_css_2l0ch1qqpad19ftfdsmj, #tinytable_pwro8an6lcdmghyyn84k th.tinytable_css_2l0ch1qqpad19ftfdsmj {  position: relative; --border-bottom: 1; --border-left: 0; --border-right: 0; --border-top: 1; --line-color-bottom: var(--tt-line-color); --line-color-left: var(--tt-line-color); --line-color-right: var(--tt-line-color); --line-color-top: var(--tt-line-color); --line-width-bottom: 0.05em; --line-width-left: 0.1em; --line-width-right: 0.1em; --line-width-top: 0.08em; --trim-bottom-left: 0%; --trim-bottom-right: 0%; --trim-left-bottom: 0%; --trim-left-top: 0%; --trim-right-bottom: 0%; --trim-right-top: 0%; --trim-top-left: 0%; --trim-top-right: 0%; ; text-align: left }
    &lt;/style&gt;
    &lt;div class=&#34;container&#34;&gt;
      &lt;table class=&#34;tinytable&#34; id=&#34;tinytable_pwro8an6lcdmghyyn84k&#34; style=&#34;width: auto; margin-left: auto; margin-right: auto;&#34; data-quarto-disable-processing=&#39;true&#39;&gt;
        
        &lt;thead&gt;
              &lt;tr&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;1&#34;&gt;$j$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;2&#34;&gt;$y_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;3&#34;&gt;$d_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;4&#34;&gt;$R_{(j)}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;5&#34;&gt;$1 - \frac{d_{(j)}}{R_{(j)}}$&lt;/th&gt;
              &lt;/tr&gt;
        &lt;/thead&gt;
        
        &lt;tbody&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;1&#34;&gt;1.00&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;2&#34;&gt;2.00&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;3&#34;&gt;2.00&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;4&#34;&gt;10.00&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;5&#34;&gt;0.80&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;1&#34;&gt;2.00&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;2&#34;&gt;5.00&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;3&#34;&gt;1.00&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;4&#34;&gt;7.00&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;5&#34;&gt;0.86&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;1&#34;&gt;3.00&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;2&#34;&gt;7.00&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;3&#34;&gt;1.00&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;4&#34;&gt;5.00&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;5&#34;&gt;0.80&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;1&#34;&gt;4.00&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;2&#34;&gt;9.00&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;3&#34;&gt;1.00&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;4&#34;&gt;4.00&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;5&#34;&gt;0.75&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;1&#34;&gt;5.00&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;2&#34;&gt;16.00&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;3&#34;&gt;2.00&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;4&#34;&gt;3.00&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;5&#34;&gt;0.33&lt;/td&gt;
                &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;
&lt;!-- hack to avoid NA insertion in last line --&gt;
&lt;p&gt;The Kaplan-Meier estimator is:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\hat{S}_{KM}(t) = \prod_{j:y_{(j)} \le t} \left(1 - \frac{d_{(j)}}{R_{(j)}} \right)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For each &lt;span class=&#34;math inline&#34;&gt;\(j\)&lt;/span&gt;, we thus take the cumulative product:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(j_1 = 0.8\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(j_2 = 0.8 \cdot 0.857 = 0.6856\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(j_3 = 0.6856 \cdot 0.8 = 0.54848\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(j_4 = 0.54848 \cdot 0.75 = 0.41136\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(j_5 = 0.41136 \cdot 0.333 = 0.1369829\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So finally, we have the survival probabilities (rounded to 3 digits):&lt;/p&gt;
&lt;!-- preamble start --&gt;

    &lt;script src=&#34;https://cdn.jsdelivr.net/gh/vincentarelbundock/tinytable@main/inst/tinytable.js&#34;&gt;&lt;/script&gt;

    &lt;script&gt;
      // Create table-specific functions using external factory
      const tableFns_9g2vmc4l85a2ai8cd30l = TinyTable.createTableFunctions(&#34;tinytable_9g2vmc4l85a2ai8cd30l&#34;);
      // tinytable span after
      window.addEventListener(&#39;load&#39;, function () {
          var cellsToStyle = [
            // tinytable style arrays after
          { positions: [ { i: &#39;5&#39;, j: 1 }, { i: &#39;5&#39;, j: 2 }, { i: &#39;5&#39;, j: 3 } ], css_id: &#39;tinytable_css_0gsa3vc5mq6m4zyan8g2&#39;,}, 
          { positions: [ { i: &#39;1&#39;, j: 1 }, { i: &#39;2&#39;, j: 1 }, { i: &#39;3&#39;, j: 1 }, { i: &#39;4&#39;, j: 1 }, { i: &#39;1&#39;, j: 2 }, { i: &#39;2&#39;, j: 2 }, { i: &#39;3&#39;, j: 2 }, { i: &#39;4&#39;, j: 2 }, { i: &#39;1&#39;, j: 3 }, { i: &#39;2&#39;, j: 3 }, { i: &#39;3&#39;, j: 3 }, { i: &#39;4&#39;, j: 3 } ], css_id: &#39;tinytable_css_qudi29yolqth1f9pviev&#39;,}, 
          { positions: [ { i: &#39;0&#39;, j: 1 }, { i: &#39;0&#39;, j: 2 }, { i: &#39;0&#39;, j: 3 } ], css_id: &#39;tinytable_css_v46u97wgn8bmam0b8xgb&#39;,}, 
          ];

          // Loop over the arrays to style the cells
          cellsToStyle.forEach(function (group) {
              group.positions.forEach(function (cell) {
                  tableFns_9g2vmc4l85a2ai8cd30l.styleCell(cell.i, cell.j, group.css_id);
              });
          });
      });
    &lt;/script&gt;

    &lt;link rel=&#34;stylesheet&#34; href=&#34;https://cdn.jsdelivr.net/gh/vincentarelbundock/tinytable@main/inst/tinytable.css&#34;&gt;
    &lt;style&gt;
    /* tinytable css entries after */
    #tinytable_9g2vmc4l85a2ai8cd30l td.tinytable_css_0gsa3vc5mq6m4zyan8g2, #tinytable_9g2vmc4l85a2ai8cd30l th.tinytable_css_0gsa3vc5mq6m4zyan8g2 {  position: relative; --border-bottom: 1; --border-left: 0; --border-right: 0; --border-top: 0; --line-color-bottom: var(--tt-line-color); --line-color-left: var(--tt-line-color); --line-color-right: var(--tt-line-color); --line-color-top: var(--tt-line-color); --line-width-bottom: 0.08em; --line-width-left: 0.1em; --line-width-right: 0.1em; --line-width-top: 0.1em; --trim-bottom-left: 0%; --trim-bottom-right: 0%; --trim-left-bottom: 0%; --trim-left-top: 0%; --trim-right-bottom: 0%; --trim-right-top: 0%; --trim-top-left: 0%; --trim-top-right: 0%; ; text-align: left }
    #tinytable_9g2vmc4l85a2ai8cd30l td.tinytable_css_qudi29yolqth1f9pviev, #tinytable_9g2vmc4l85a2ai8cd30l th.tinytable_css_qudi29yolqth1f9pviev { text-align: left }
    #tinytable_9g2vmc4l85a2ai8cd30l td.tinytable_css_v46u97wgn8bmam0b8xgb, #tinytable_9g2vmc4l85a2ai8cd30l th.tinytable_css_v46u97wgn8bmam0b8xgb {  position: relative; --border-bottom: 1; --border-left: 0; --border-right: 0; --border-top: 1; --line-color-bottom: var(--tt-line-color); --line-color-left: var(--tt-line-color); --line-color-right: var(--tt-line-color); --line-color-top: var(--tt-line-color); --line-width-bottom: 0.05em; --line-width-left: 0.1em; --line-width-right: 0.1em; --line-width-top: 0.08em; --trim-bottom-left: 0%; --trim-bottom-right: 0%; --trim-left-bottom: 0%; --trim-left-top: 0%; --trim-right-bottom: 0%; --trim-right-top: 0%; --trim-top-left: 0%; --trim-top-right: 0%; ; text-align: left }
    &lt;/style&gt;
    &lt;div class=&#34;container&#34;&gt;
      &lt;table class=&#34;tinytable&#34; id=&#34;tinytable_9g2vmc4l85a2ai8cd30l&#34; style=&#34;width: auto; margin-left: auto; margin-right: auto;&#34; data-quarto-disable-processing=&#39;true&#39;&gt;
        
        &lt;thead&gt;
              &lt;tr&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;1&#34;&gt;$j$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;2&#34;&gt;$1 - \frac{d_{(j)}}{R_{(j)}}$&lt;/th&gt;
                &lt;th scope=&#34;col&#34; data-row=&#34;0&#34; data-col=&#34;3&#34;&gt;$\hat{S}_{KM}(t)$&lt;/th&gt;
              &lt;/tr&gt;
        &lt;/thead&gt;
        
        &lt;tbody&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;1&#34;&gt;1.00&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;2&#34;&gt;0.80&lt;/td&gt;
                  &lt;td data-row=&#34;1&#34; data-col=&#34;3&#34;&gt;0.80&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;1&#34;&gt;2.00&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;2&#34;&gt;0.86&lt;/td&gt;
                  &lt;td data-row=&#34;2&#34; data-col=&#34;3&#34;&gt;0.69&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;1&#34;&gt;3.00&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;2&#34;&gt;0.80&lt;/td&gt;
                  &lt;td data-row=&#34;3&#34; data-col=&#34;3&#34;&gt;0.55&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;1&#34;&gt;4.00&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;2&#34;&gt;0.75&lt;/td&gt;
                  &lt;td data-row=&#34;4&#34; data-col=&#34;3&#34;&gt;0.41&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;1&#34;&gt;5.00&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;2&#34;&gt;0.33&lt;/td&gt;
                  &lt;td data-row=&#34;5&#34; data-col=&#34;3&#34;&gt;0.14&lt;/td&gt;
                &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;
&lt;!-- hack to avoid NA insertion in last line --&gt;
&lt;p&gt;We can now represent graphically the Kaplan-Meier estimator:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/what-is-survival-analysis/index_files/figure-html/unnamed-chunk-13-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;To draw this survival curve, remember that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the x-axis corresponds to the &lt;code&gt;time&lt;/code&gt; variable in the initial dataset, and&lt;/li&gt;
&lt;li&gt;the y-axis corresponds to the survival probabilities found above.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;In R&lt;/h2&gt;
&lt;p&gt;We now compare our results with the results found in R.&lt;/p&gt;
&lt;p&gt;We first create the dataset with the time and event variables:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# create dataset
dat &amp;lt;- data.frame(
  time = c(3, 5, 7, 2, 18, 16, 2, 9, 16, 5),
  event = c(0, 1, 1, 1, 0, 1, 1, 1, 1, 0)
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We then run the Kaplan-Meier estimator with the &lt;code&gt;survfit()&lt;/code&gt; and &lt;code&gt;Surv()&lt;/code&gt; functions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# KM
library(survival)

km &amp;lt;- survfit(Surv(time, event) ~ 1,
  data = dat
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice that the &lt;code&gt;Surv()&lt;/code&gt; function accepts two arguments:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;the &lt;code&gt;time&lt;/code&gt; variable, and&lt;/li&gt;
&lt;li&gt;the &lt;code&gt;event&lt;/code&gt; variable.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The &lt;code&gt;~ 1&lt;/code&gt; in the &lt;code&gt;survfit()&lt;/code&gt; function indicates that we estimate the Kaplan-Meier without any grouping. See more on this later in the post.&lt;/p&gt;
&lt;p&gt;Finally, we display the results and draw the Kaplan-Meier plot:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# results
summary(km)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Call: survfit(formula = Surv(time, event) ~ 1, data = dat)
## 
##  time n.risk n.event survival std.err lower 95% CI upper 95% CI
##     2     10       2    0.800   0.126       0.5868        1.000
##     5      7       1    0.686   0.151       0.4447        1.000
##     7      5       1    0.549   0.172       0.2963        1.000
##     9      4       1    0.411   0.176       0.1782        0.950
##    16      3       2    0.137   0.126       0.0225        0.834&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# plot
plot(km,
  xlab = &amp;quot;Time&amp;quot;,
  ylab = &amp;quot;Survival probability&amp;quot;,
  conf.int = FALSE
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/what-is-survival-analysis/index_files/figure-html/unnamed-chunk-16-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The survival probabilities can be found in the &lt;code&gt;survival&lt;/code&gt; column. Remark that results by hand and in R are similar (any difference with the results by hand is due to rounding).&lt;/p&gt;
&lt;p&gt;Alternatively, we can use the &lt;code&gt;ggsurvplot()&lt;/code&gt; function within the &lt;code&gt;{survminer}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(survminer)

# plot
ggsurvplot(km,
  conf.int = FALSE,
  legend = &amp;quot;none&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/what-is-survival-analysis/index_files/figure-html/unnamed-chunk-17-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note that the crosses on the survival curve denote the censored observations.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The advantage with the &lt;code&gt;ggsurvplot()&lt;/code&gt; function is that it is easy to draw the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#median&#34;&gt;median&lt;/a&gt; survival directly on the plot:&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggsurvplot(km,
  conf.int = FALSE,
  surv.median.line = &amp;quot;hv&amp;quot;,
  legend = &amp;quot;none&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/what-is-survival-analysis/index_files/figure-html/unnamed-chunk-18-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;To find the median survival:&lt;a href=&#34;#fn4&#34; class=&#34;footnote-ref&#34; id=&#34;fnref4&#34;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(km)$table[&amp;quot;median&amp;quot;]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## median 
##      9&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# or more simply
km&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Call: survfit(formula = Surv(time, event) ~ 1, data = dat)
## 
##       n events median 0.95LCL 0.95UCL
## [1,] 10      7      9       5      NA&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Suppose that the event of interest is death:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;At time zero, the survival probability is 1 (100% of the subjects are alive).&lt;/li&gt;
&lt;li&gt;The median indicates that the median survival time is 9 years.&lt;a href=&#34;#fn5&#34; class=&#34;footnote-ref&#34; id=&#34;fnref5&#34;&gt;&lt;sup&gt;5&lt;/sup&gt;&lt;/a&gt; This is the time at which the survival &lt;span class=&#34;math inline&#34;&gt;\(S(t)\)&lt;/span&gt; is 50%. In other words, is the time after which half of the subjects are expected to have died.&lt;/li&gt;
&lt;li&gt;From the plot, we also see that &lt;span class=&#34;math inline&#34;&gt;\(S(5) = P(T &amp;gt; 5 \text{ years}) =\)&lt;/span&gt; Probability of survival of more than 5 years for these subjects = 68.6%. This means that 68.6% of all subjects survive longer than 5 years, and that 31.4% of all subjects die within the first 5 years.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For the sake of completeness, let’s do another example with a much larger dataset; the &lt;code&gt;tongue&lt;/code&gt; dataset within the &lt;code&gt;{KMsurv}&lt;/code&gt; package.&lt;a href=&#34;#fn6&#34; class=&#34;footnote-ref&#34; id=&#34;fnref6&#34;&gt;&lt;sup&gt;6&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load data
library(KMsurv)
data(tongue)

# preview data
head(tongue)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   type time delta
## 1    1    1     1
## 2    1    3     1
## 3    1    3     1
## 4    1    4     1
## 5    1   10     1
## 6    1   13     1&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;type&lt;/code&gt; is the tumor DNA profile (1 = aneuploid tumor, 2 = diploid tumor)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;time&lt;/code&gt; is the time to death or on-study time (in weeks)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;delta&lt;/code&gt; is the death indicator (0 = alive, 1 = dead)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For this example, we focus on the aneuploid type:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;anaploid &amp;lt;- subset(tongue, type == 1)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can now plot the estimated survival function and estimate the median time to death. Since it is an estimator, we can also construct a confidence interval for the estimated survival at each time &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt; and for the estimated median survival time.&lt;a href=&#34;#fn7&#34; class=&#34;footnote-ref&#34; id=&#34;fnref7&#34;&gt;&lt;sup&gt;7&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# results
fit &amp;lt;- survfit(Surv(time, delta) ~ 1,
  data = anaploid,
  conf.type = &amp;quot;log-log&amp;quot;
)

fit&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Call: survfit(formula = Surv(time, delta) ~ 1, data = anaploid, conf.type = &amp;quot;log-log&amp;quot;)
## 
##       n events median 0.95LCL 0.95UCL
## [1,] 52     31     93      65     157&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# plot
ggsurvplot(fit,
  surv.median.line = &amp;quot;hv&amp;quot;,
  legend = &amp;quot;none&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/what-is-survival-analysis/index_files/figure-html/unnamed-chunk-22-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The median survival time is estimated to be 93 weeks, with a 95% confidence interval between 65 and 157 weeks.&lt;/p&gt;
&lt;p&gt;Kaplan-Meier curves can be seen as &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt; for survival data. We now focus on the second branch of statistics, &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis testing&lt;/a&gt; which allows to draw conclusions on the population based on a sample (see a quick reminder about the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;difference between population and sample&lt;/a&gt; if you need).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;hypothesis-testing&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Hypothesis testing&lt;/h1&gt;
&lt;p&gt;Hypothesis testing in the field of survival analysis mostly concerns:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The hazard function of &lt;strong&gt;one population&lt;/strong&gt;: in this case we test whether a censored sample comes from a population with a known hazard function &lt;span class=&#34;math inline&#34;&gt;\(h_0(t)\)&lt;/span&gt;. For example, we may be interested to compare survival in a sample of patients to the survival in the overall population (derived from the life tables).&lt;/li&gt;
&lt;li&gt;The comparison of the hazard function of &lt;strong&gt;two or more populations&lt;/strong&gt;: in this case we are interested in assessing whether there are differences in survival among different groups of subjects. For example:
&lt;ul&gt;
&lt;li&gt;2 groups: we are interested in comparing survival for female and male colon cancer patients&lt;/li&gt;
&lt;li&gt;3 groups or more: we are interested in comparing survival for melanoma cancer patients according to their treatments (with treatments A, B and C for example)&lt;a href=&#34;#fn8&#34; class=&#34;footnote-ref&#34; id=&#34;fnref8&#34;&gt;&lt;sup&gt;8&lt;/sup&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&#34;log-rank-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Log-rank test&lt;/h2&gt;
&lt;p&gt;In this article, we focus on comparing survival between two groups using the &lt;strong&gt;log-rank test&lt;/strong&gt; (also known as Mantel-Cox test). This test is the most common hypothesis test to compare survival between two groups.&lt;/p&gt;
&lt;p&gt;The intuition behind the test is that if the two groups have different hazard rates, the two survival curves (so their slopes) will differ. More precisely, the log-rank test compares the observed number of events in each group to what would be expected if the survival curves were identical (i.e., if the null hypothesis were true).&lt;/p&gt;
&lt;p&gt;Note that, as for the Kaplan-Meier estimator, the log-rank test is a nonparametric test, which makes no assumptions about the survival distributions.&lt;/p&gt;
&lt;p&gt;For this example, consider the following dataset:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;##    patient group time event
## 1        1     1  4.1     1
## 2        2     1  7.8     0
## 3        3     1 10.0     1
## 4        4     1 10.0     1
## 5        5     1 12.3     0
## 6        6     1 17.2     1
## 7        7     2  9.7     1
## 8        8     2 10.0     1
## 9        9     2 11.1     0
## 10      10     2 13.1     0
## 11      11     2 19.7     1
## 12      12     2 24.1     0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;patient&lt;/code&gt; is the patient’s identifier&lt;/li&gt;
&lt;li&gt;&lt;code&gt;group&lt;/code&gt; is the group (group 1 or 2)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;time&lt;/code&gt; is the time to death (in years)&lt;a href=&#34;#fn9&#34; class=&#34;footnote-ref&#34; id=&#34;fnref9&#34;&gt;&lt;sup&gt;9&lt;/sup&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;event&lt;/code&gt; is the event status (0 = censored, 1 = death)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Suppose we are interested in comparing group 1 and 2 in terms of survival, that is, we compare survival curves between the 2 groups:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0 : S_1(t) = S_2(t)\)&lt;/span&gt; for all &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1 : S_1(t) \ne S_2(t)\)&lt;/span&gt; for some &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;It is a statistical test, so if the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &amp;lt; &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; (usually 0.05), we reject the null hypothesis and we conclude that survival (or the time to event) is significantly different between the two groups considered.&lt;/p&gt;
&lt;p&gt;To perform the log-rank test, the following test statistic will be useful:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{eqnarray}
U &amp;amp;=&amp;amp; \sum_{j=1}^r w(y_{(j)})\left(O_j - E_j\right) \\
&amp;amp;=&amp;amp; \sum_{j=1}^r w(y_{(j)})\left( d_{(j)1} - \frac{d_{(j)}R_{(j)1}}{R_{(j)}}\right)
\end{eqnarray}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;with &lt;span class=&#34;math inline&#34;&gt;\(U^{obs} = \frac{U}{\sqrt{Var(U)}} \sim N(0,1)\)&lt;/span&gt; and&lt;a href=&#34;#fn10&#34; class=&#34;footnote-ref&#34; id=&#34;fnref10&#34;&gt;&lt;sup&gt;10&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{eqnarray}
Var(U) &amp;amp;=&amp;amp; \sum_{j=1}^r w^2(y_{(j)}) \frac{N_{(j)}}{ D_{(j)}  }\\
&amp;amp;=&amp;amp; \sum_{j=1}^r w^2(y_{(j)}) \frac{ d_{(j)} \frac{R_{(j)1}}{R_{(j)} } \left( 1 - \frac{R_{(j)1}}{R_{(j)} } \right) \left( R_{(j)} - d_{(j)}\right) }{ R_{(j)} - 1  }
\end{eqnarray}\]&lt;/span&gt;&lt;/p&gt;
&lt;div id=&#34;by-hand-1&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;By hand&lt;/h3&gt;
&lt;p&gt;As for the Kaplan-Meier estimator by hand, it is best to also fill in a table for the log-rank test by hand.&lt;/p&gt;
&lt;p&gt;Let’s present the final table and comment below on how to fill it, column by column:&lt;/p&gt;
&lt;table style=&#34;width:100%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;5%&#34; /&gt;
&lt;col width=&#34;6%&#34; /&gt;
&lt;col width=&#34;7%&#34; /&gt;
&lt;col width=&#34;7%&#34; /&gt;
&lt;col width=&#34;7%&#34; /&gt;
&lt;col width=&#34;7%&#34; /&gt;
&lt;col width=&#34;6%&#34; /&gt;
&lt;col width=&#34;6%&#34; /&gt;
&lt;col width=&#34;5%&#34; /&gt;
&lt;col width=&#34;5%&#34; /&gt;
&lt;col width=&#34;10%&#34; /&gt;
&lt;col width=&#34;6%&#34; /&gt;
&lt;col width=&#34;6%&#34; /&gt;
&lt;col width=&#34;11%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(j\)&lt;/span&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(y_{(j)}\)&lt;/span&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(d_{(j)1}\)&lt;/span&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(R_{(j)1}\)&lt;/span&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(d_{(j)2}\)&lt;/span&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(R_{(j)2}\)&lt;/span&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(d_{(j)}\)&lt;/span&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(R_{(j)}\)&lt;/span&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(E_{j}\)&lt;/span&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(O_{j}\)&lt;/span&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(O_{j} - E_{j}\)&lt;/span&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(N_{(j)}\)&lt;/span&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(D_{(j)}\)&lt;/span&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(N_{(j)}/D_{(j)}\)&lt;/span&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;4.1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;6&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;6&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;12&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.5&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.5&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2.75&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;11&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.25&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;9.7&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;4&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;6&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.4&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;-0.4&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2.16&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.24&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;3&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;4&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;5&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;3&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1.333&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.667&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;4.44&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;8&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.555&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;4&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;17.2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;3&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.333&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.667&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.44&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.22&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;5&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;19.7&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.00&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.00&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(Total\)&lt;/span&gt;&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;4&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;3&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;7&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2.566&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1.433&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1.265&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Column &lt;span class=&#34;math inline&#34;&gt;\(j\)&lt;/span&gt;&lt;/strong&gt; is the number of distinct event times. We see that there are 5 (ignoring censored observations), so we write 1 to 5 in the table.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Column &lt;span class=&#34;math inline&#34;&gt;\(y_{(j)}\)&lt;/span&gt;&lt;/strong&gt; is the ordered distinct event times:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;4.1&lt;/em&gt;, &lt;em&gt;9.7&lt;/em&gt;, &lt;em&gt;10&lt;/em&gt;, &lt;em&gt;17.2&lt;/em&gt; and &lt;em&gt;19.7&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Column &lt;span class=&#34;math inline&#34;&gt;\(d_{(j)1}\)&lt;/span&gt;&lt;/strong&gt; is the number of observations for each distinct event time, for group 1:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## time
##  4.1   10 17.2 
##    1    2    1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When there is no event, we simply write 0 in the table.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Column &lt;span class=&#34;math inline&#34;&gt;\(R_{(j)1}\)&lt;/span&gt;&lt;/strong&gt; is the remaining number of patients at risk, for group 1. For this, the distribution of time (censored and not censored, for group 1) is useful:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## time
##  4.1  7.8   10 12.3 17.2 
##    1    1    2    1    1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We see that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;At the beginning, there are 6 patients&lt;/li&gt;
&lt;li&gt;Before time 9.7, there are 4 patients left (6 - 1 who had the event at time 4.1 - 1 who was censored at time 7.8)&lt;/li&gt;
&lt;li&gt;Before time 10, there are 4 patients left (6 - 2)&lt;/li&gt;
&lt;li&gt;Before time 17.2, there are 1 patient left (6 - 5)&lt;/li&gt;
&lt;li&gt;Before time 19.7, there are 0 patient left (6 - 6)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Columns &lt;span class=&#34;math inline&#34;&gt;\(d_{(j)2}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(R_{(j)2}\)&lt;/span&gt;&lt;/strong&gt; follow the same principle, but for group 2 this time. So we have, respectively for &lt;span class=&#34;math inline&#34;&gt;\(d_{(j)2}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(R_{(j)2}\)&lt;/span&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## time
##  9.7   10 19.7 
##    1    1    1&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## time
##  9.7   10 11.1 13.1 19.7 24.1 
##    1    1    1    1    1    1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Columns &lt;span class=&#34;math inline&#34;&gt;\(d_{(j)}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(R_{(j)}\)&lt;/span&gt;&lt;/strong&gt; also follow the same principle, but this time considering both groups. So we have, respectively for &lt;span class=&#34;math inline&#34;&gt;\(d_{(j)}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(R_{(j)}\)&lt;/span&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## time
##  4.1  9.7   10 17.2 19.7 
##    1    1    3    1    1&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## time
##  4.1  7.8  9.7   10 11.1 12.3 13.1 17.2 19.7 24.1 
##    1    1    1    3    1    1    1    1    1    1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Column &lt;span class=&#34;math inline&#34;&gt;\(E_{j}\)&lt;/span&gt;&lt;/strong&gt; is the expected number of events in the first group assuming that &lt;span class=&#34;math inline&#34;&gt;\(h_1 \equiv h_2\)&lt;/span&gt;. It is obtained as follows&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[ E_{j} = \frac{d_{(j)}R_{(j)1}}{R_{(j)}}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Column &lt;span class=&#34;math inline&#34;&gt;\(O_{j}\)&lt;/span&gt;&lt;/strong&gt; is the observed number of events in the first group, so it is equal to the &lt;span class=&#34;math inline&#34;&gt;\(d_{(j)1}\)&lt;/span&gt; column.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Column &lt;span class=&#34;math inline&#34;&gt;\(O_{j} - E_{j}\)&lt;/span&gt;&lt;/strong&gt; is straightforward.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Column &lt;span class=&#34;math inline&#34;&gt;\(N_{(j)}\)&lt;/span&gt;&lt;/strong&gt; is defined as follows&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[N_{(j)} = d_{(j)} \frac{R_{(j)1}}{R_{(j)} } \left( 1 - \frac{R_{(j)1}}{R_{(j)} } \right) \left( R_{(j)} - d_{(j)}\right)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Column &lt;span class=&#34;math inline&#34;&gt;\(D_{(j)}\)&lt;/span&gt;&lt;/strong&gt; is &lt;span class=&#34;math inline&#34;&gt;\(R_{(j)} - 1\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Column &lt;span class=&#34;math inline&#34;&gt;\(N_{(j)}/D_{(j)}\)&lt;/span&gt;&lt;/strong&gt; is straightforward.&lt;/p&gt;
&lt;p&gt;Since &lt;span class=&#34;math inline&#34;&gt;\(w(y_{(j)}) = w^2(y_{(j)}) = 1\)&lt;/span&gt; for a log-rank test, we have&lt;a href=&#34;#fn11&#34; class=&#34;footnote-ref&#34; id=&#34;fnref11&#34;&gt;&lt;sup&gt;11&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[ U^{obs} = \frac{U}{\sqrt{Var(U)}} = \frac{1.434}{\sqrt{1.265}} = 1.275.\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;We reject &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt; if &lt;span class=&#34;math inline&#34;&gt;\(|U^{obs}|&amp;gt;z_{1-\alpha/2}\)&lt;/span&gt;, so at the 5% significance level we reject &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt; if &lt;span class=&#34;math inline&#34;&gt;\(|U^{obs}|&amp;gt;z_{0.975}=1.96\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;We have &lt;span class=&#34;math inline&#34;&gt;\(|U^{obs}| = 1.275 &amp;lt; z_{0.975}=1.96\)&lt;/span&gt;. Hence, at the 5% significance level we do not reject &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;. This means that, based on the data, we are not able to conclude that survival is different between the two groups (which is equivalent than saying that we do not reject the hypothesis that survival is equal between the two groups).&lt;/p&gt;
&lt;p&gt;If you are interested in computing the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &lt;span class=&#34;math inline&#34;&gt;\(= 2\times P(Z&amp;gt;1.275) = 2 \times 0.101 = 0.202 &amp;gt; 0.05\)&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r-1&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;In R&lt;/h3&gt;
&lt;p&gt;We now compare our results in R with the &lt;code&gt;survdiff()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- data.frame(
  group = c(rep(1, 6), rep(2, 6)),
  time = c(4.1, 7.8, 10, 10, 12.3, 17.2, 9.7, 10, 11.1, 13.1, 19.7, 24.1),
  event = c(1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0)
)

dat&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    group time event
## 1      1  4.1     1
## 2      1  7.8     0
## 3      1 10.0     1
## 4      1 10.0     1
## 5      1 12.3     0
## 6      1 17.2     1
## 7      2  9.7     1
## 8      2 10.0     1
## 9      2 11.1     0
## 10     2 13.1     0
## 11     2 19.7     1
## 12     2 24.1     0&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;survdiff(Surv(time, event) ~ group,
  data = dat
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Call:
## survdiff(formula = Surv(time, event) ~ group, data = dat)
## 
##         N Observed Expected (O-E)^2/E (O-E)^2/V
## group=1 6        4     2.57     0.800      1.62
## group=2 6        3     4.43     0.463      1.62
## 
##  Chisq= 1.6  on 1 degrees of freedom, p= 0.2&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Alternatively, we can use the &lt;code&gt;ggsurvplot()&lt;/code&gt; function to draw the survival curves and perform the log-rank test at the same time:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;fit &amp;lt;- survfit(Surv(time, event) ~ group, data = dat)

ggsurvplot(fit,
  pval = TRUE,
  pval.method = TRUE
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/what-is-survival-analysis/index_files/figure-html/unnamed-chunk-30-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;As we can see, the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values and the conclusions are the same (any difference with the results by hand is due to rounding).&lt;/p&gt;
&lt;p&gt;As for the Kaplan-Meier estimation, we do another example on a larger dataset. Consider the data on the times until staphylococcus infection of burn patients, also available in the &lt;code&gt;{KMsurv}&lt;/code&gt;:&lt;a href=&#34;#fn12&#34; class=&#34;footnote-ref&#34; id=&#34;fnref12&#34;&gt;&lt;sup&gt;12&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load data
data(burn)

# preview data
head(burn)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   Obs Z1 Z2 Z3 Z4 Z5 Z6 Z7 Z8 Z9 Z10 Z11 T1 D1 T2 D2 T3 D3
## 1   1  0  0  0 15  0  0  1  1  0   0   2 12  0 12  0 12  0
## 2   2  0  0  1 20  0  0  1  0  0   0   4  9  0  9  0  9  0
## 3   3  0  0  1 15  0  0  0  1  1   0   2 13  0 13  0  7  1
## 4   4  0  0  0 20  1  0  1  0  0   0   2 11  1 29  0 29  0
## 5   5  0  0  1 70  1  1  1  1  0   0   2 28  1 31  0  4  1
## 6   6  0  0  1 20  1  0  1  0  0   0   4 11  0 11  0  8  1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using the log-rank test, we want to test the hypothesis of difference in the time to staphylococcus infection (&lt;code&gt;T3&lt;/code&gt; variable) between patients whose burns were cared for with a routine bathing care method (&lt;code&gt;Z1 = 0&lt;/code&gt;) versus those whose body cleansing was initially performed using 4% chlorhexidine gluconate (&lt;code&gt;Z1 = 1&lt;/code&gt;). The event indicator is in variable &lt;code&gt;D3&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;For this test, we use a two-sided alternative and a 5% significance level.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# fit
fit &amp;lt;- survfit(Surv(T3, D3) ~ Z1, data = burn)

# plot with log-rank test
ggsurvplot(fit,
  pval = TRUE,
  pval.method = TRUE
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/what-is-survival-analysis/index_files/figure-html/unnamed-chunk-32-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;In the sample&lt;/em&gt;, it seems that the time to infection for patients with routine bathing (&lt;code&gt;Z1 = 0&lt;/code&gt;) is smaller than for patients with body cleansing (&lt;code&gt;Z1 = 1&lt;/code&gt;). This is the case because the percentage of patients who have not experienced the infection decreases more quickly, so the hazard rate is greater.&lt;/p&gt;
&lt;p&gt;However, this conclusion cannot be generalized to the &lt;em&gt;population&lt;/em&gt; without performing a sound statistical test. And based on the result of the log-rank test, we do not reject the hypothesis that time to infection is the same between the two groups of patients (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.051).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;to-go-further&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;To go further&lt;/h1&gt;
&lt;p&gt;In this article, we have presented what is survival analysis, when, why and how to use it. We discussed about censoring and survival curves. We showed how to estimate the survival function via the Kaplan-Meier estimator and how to test survival between two groups via the log-rank test. We illustrated these approaches both by hand and in R.&lt;/p&gt;
&lt;p&gt;As you noticed, we did not show how to &lt;em&gt;model&lt;/em&gt; survival data. There are several regression models that can be applied to survival data, the most common one being the semiparametric Cox Proportional Hazards model &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-cox1972regression&#34;&gt;1972&lt;/a&gt;)&lt;/span&gt;. It originated from the medical area to investigate and assess the relationship between the survival times of patients and their corresponding predictor variables.&lt;/p&gt;
&lt;p&gt;We have seen that the Kaplan-Meier estimator is useful to visualize survival between groups and the log-rank test to test whether survival significantly differs between groups (so both approaches use a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;categorical variable&lt;/a&gt; as predictor). However, it does not work well for assessing the effect of &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#quantitative&#34;&gt;quantitative predictor&lt;/a&gt;. The Cox model has the advantage that it works for both quantitative as well as for categorical predictors, and for several risk factors at the same time (so it can model the effect of multiple variables at once).&lt;/p&gt;
&lt;p&gt;With the Cox model, we model the impact of different factors &lt;span class=&#34;math inline&#34;&gt;\(X_1, X_2, \ldots, X_q\)&lt;/span&gt; on survival via their impact on the hazard function:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[h(t|\textbf{X}) = h_0 (t) exp(\beta_1 X_1 + \beta_2 X_2 + \cdots + \beta_q X_q),\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(h(t|\textbf{X})\)&lt;/span&gt; is the instantaneous death rate conditional on having survived up to time &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(h_0 (t)\)&lt;/span&gt; is the population-level baseline hazard – the underlying hazard function. It describes how the average person’s risk evolves over time.&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(exp(\beta_1 X_1 + \beta_2 X_2 + \cdots + \beta_q X_q)\)&lt;/span&gt; describes how covariates affect the hazard. In particular, a unit increase in &lt;span class=&#34;math inline&#34;&gt;\(x_i\)&lt;/span&gt; leads to an increase of the hazard by a factor of &lt;span class=&#34;math inline&#34;&gt;\(\exp(\beta_i)\)&lt;/span&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This post aimed at presenting the introductory concepts in survival analysis, so this model will be developed in another post. In the meantime, if you would like to learn more about modeling survival data (thanks to the Cox model and other models), see this &lt;a href=&#34;https://rviews.rstudio.com/2022/09/06/deep-survival/&#34;&gt;post&lt;/a&gt; from Joseph Rickert.&lt;/p&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-cox1972regression&#34; class=&#34;csl-entry&#34;&gt;
Cox, David R. 1972. &lt;span&gt;“Regression Models and Life-Tables.”&lt;/span&gt; &lt;em&gt;Journal of the Royal Statistical Society: Series B (Methodological)&lt;/em&gt; 34 (2): 187–202.
&lt;/div&gt;
&lt;div id=&#34;ref-kaplan1958nonparametric&#34; class=&#34;csl-entry&#34;&gt;
Kaplan, Edward L, and Paul Meier. 1958. &lt;span&gt;“Nonparametric Estimation from Incomplete Observations.”&lt;/span&gt; &lt;em&gt;Journal of the American Statistical Association&lt;/em&gt; 53 (282): 457–81.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;Note that in survival analysis, the precision of the estimators (and the power of the tests) does not depend on the number of patients but on the number of events. So it is best to have many observations where the event does occur for the analyses to be effective. Here we work on a small sample for the sake of illustration.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Note that the &lt;code&gt;time&lt;/code&gt; variable can be expressed in other units, such as seconds, days, weeks, months, etc.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;Median is preferred over mean in survival analysis because survival functions are often skewed to the right. The mean is often influenced by &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt;, whereas the median is not. See a discussion comparing the two in this &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#mean-vs.-median&#34;&gt;section&lt;/a&gt;.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;Note that if the survival curve does not cross 50% (because survival is greater than 50% at the last time point), then the median survival cannot be computed and is simply undefined.&lt;a href=&#34;#fnref4&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn5&#34;&gt;&lt;p&gt;Note that the median survival is expressed in the same unit than the unit of the &lt;code&gt;time&lt;/code&gt; variable in the initial dataset. So if the time unit was months, the median survival time would be 9 months.&lt;a href=&#34;#fnref5&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn6&#34;&gt;&lt;p&gt;More information about the dataset can be found on &lt;a href=&#34;https://cran.r-project.org/web/packages/KMsurv/&#34;&gt;CRAN&lt;/a&gt; or with &lt;code&gt;?tongue&lt;/code&gt;.&lt;a href=&#34;#fnref6&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn7&#34;&gt;&lt;p&gt;See the reason we use &lt;code&gt;log-log&lt;/code&gt; for the confidence interval in this &lt;a href=&#34;https://stats.stackexchange.com/questions/361354/choosing-conf-type-for-survfit-in-r&#34;&gt;thread&lt;/a&gt;.&lt;a href=&#34;#fnref7&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn8&#34;&gt;&lt;p&gt;Note that if the groups to compare have a natural ordering (such as the educational level; none, low, medium, high), tests that take it into consideration have more power to detect significant effects. These tests are referred as tests for trend.&lt;a href=&#34;#fnref8&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn9&#34;&gt;&lt;p&gt;Remember that the time unit can be different than years.&lt;a href=&#34;#fnref9&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn10&#34;&gt;&lt;p&gt;This is the case for large samples. The example described here does not meet this condition, but we still show it as an illustration.&lt;a href=&#34;#fnref10&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn11&#34;&gt;&lt;p&gt;Note that other weights can be considered, but this is beyond the scope of this article.&lt;a href=&#34;#fnref11&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn12&#34;&gt;&lt;p&gt;More information about the dataset can be found on &lt;a href=&#34;https://cran.r-project.org/web/packages/KMsurv/&#34;&gt;CRAN&lt;/a&gt; or with &lt;code&gt;?burn&lt;/code&gt;.&lt;a href=&#34;#fnref12&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Paper: &#39;EpiLPS: A fast and flexible Bayesian tool for estimation of the time-varying reproduction number&#39;</title>
      <link>https://statsandr.com/blog/paper-epilps-a-fast-and-flexible-bayesian-tool-for-estimation-of-the-time-varying-reproduction-number/</link>
      <pubDate>Wed, 19 Oct 2022 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/paper-epilps-a-fast-and-flexible-bayesian-tool-for-estimation-of-the-time-varying-reproduction-number/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#motivation&#34; id=&#34;toc-motivation&#34;&gt;Motivation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#getting-started&#34; id=&#34;toc-getting-started&#34;&gt;Getting started&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#a-simulated-example&#34; id=&#34;toc-a-simulated-example&#34;&gt;A simulated example&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#smoothing-the-epidemic-curve-and-estimating-mathcalr_t&#34; id=&#34;toc-smoothing-the-epidemic-curve-and-estimating-mathcalr_t&#34;&gt;Smoothing the epidemic curve and estimating &lt;span class=&#34;math inline&#34;&gt;\(\mathcal{R}_t\)&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#usa-hospitalization-data&#34; id=&#34;toc-usa-hospitalization-data&#34;&gt;USA hospitalization data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;images/EpiLPS.PNG&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;A colleague (and friend) of mine recently published a research paper entitled “EpiLPS: A fast and flexible Bayesian tool for estimation of the time-varying reproduction number” in PLoS Computational Biology.&lt;/p&gt;
&lt;p&gt;I am not in the habit of sharing research paper to which I did not contribute. Nevertheless, I would like to make an exception with this one because I strongly believe that the method developed in the paper deserves to be known, especially for anyone working in epidemiology.&lt;/p&gt;
&lt;p&gt;Below is the motivation behind the article, as well as an illustration on simulated and real data (US hospitalization data). More information can be found in the &lt;a href=&#34;https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1010618&#34;&gt;paper&lt;/a&gt; and on the accompanying &lt;a href=&#34;https://epilps.com/&#34;&gt;website&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;motivation&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Motivation&lt;/h1&gt;
&lt;p&gt;EpiLPS &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-gressani2022epilps&#34; role=&#34;doc-biblioref&#34;&gt;Gressani et al. 2022&lt;/a&gt;)&lt;/span&gt; is a methodology for flexible Bayesian inference of the time-varying reproduction number &lt;span class=&#34;math inline&#34;&gt;\(\mathcal{R}_t\)&lt;/span&gt;; the average number of secondary cases generated by an infected agent at time &lt;span class=&#34;math inline&#34;&gt;\(t\)&lt;/span&gt;. This is a key epidemiological parameter that informs about the transmission potential of an infectious disease and can be used by public health authorities to gauge the effectiveness of interventions and propose an orientation for future control strategies.&lt;/p&gt;
&lt;p&gt;This metric has gained in popularity during the SARS-CoV-2 pandemic with wide media coverage as its meaning is easily and intuitively grasped. Put simply, when &lt;span class=&#34;math inline&#34;&gt;\(\mathcal{R} &amp;lt; 1\)&lt;/span&gt;, the signal is encouraging as the epidemic is under control and will eventually vanish. On the contrary, a value of &lt;span class=&#34;math inline&#34;&gt;\(\mathcal{R} &amp;gt; 1\)&lt;/span&gt; means that the disease keeps spreading and infections are witnessing an expansionary impact. Having a robust and reliable tool to compute the reproduction number from infectious disease data is therefore crucial.&lt;/p&gt;
&lt;p&gt;A group of researchers in the EpiPose team from Hasselt University (Belgium), Leiden University (The Netherlands), and the University of Bern (Switzerland) have recently developed a new methodology for estimating the instantaneous reproduction number from incidence time series data for a given serial interval distribution (the time elapsed between the onset of symptoms in an infector and the onset of symptoms of secondary cases).&lt;/p&gt;
&lt;p&gt;They termed their approach EpiLPS for “&lt;strong&gt;Epi&lt;/strong&gt;demiological modeling with &lt;strong&gt;L&lt;/strong&gt;aplacian-&lt;strong&gt;P&lt;/strong&gt;-&lt;strong&gt;S&lt;/strong&gt;plines” as Laplace approximations and P-splines smoothers are key ingredients that form the backbone of the proposed methodology.&lt;/p&gt;
&lt;p&gt;&lt;br&gt;
&lt;img src=&#34;images/Infographic_EpiLPS.png&#34; style=&#34;width:100.0%&#34; /&gt;
&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The EpiLPS model assumes that the observed reported cases (by reporting date or date of symptom onset) are governed by a negative binomial distribution. As such, it allows to take the feature of overdispersion into account, contrary to a Poisson model. The epidemic curve is smoothed with P-splines (where posterior estimates of latent variables are computed via Laplace approximations) in a first step and a renewal equation model is used in a second step as a bridge between the reproduction number and the estimated spline coefficients through a “plug-in” method.&lt;/p&gt;
&lt;p&gt;The authors also explain the main difference between EpiLPS and EpiEstim, a well established approached for estimating &lt;span class=&#34;math inline&#34;&gt;\(\mathcal{R}_t\)&lt;/span&gt; in real-time developed by &lt;span class=&#34;citation&#34;&gt;Cori et al. (&lt;a href=&#34;#ref-cori2013new&#34; role=&#34;doc-biblioref&#34;&gt;2013&lt;/a&gt;)&lt;/span&gt; and make extensive comparisons between the two approaches under different epidemic scenarios.&lt;/p&gt;
&lt;p&gt;An interesting feature of EpiLPS is that the user can choose between a fully “sampling-free” path, where model hyperparameters are fixed at their &lt;em&gt;maximum a posteriori&lt;/em&gt; (LPSMAP) or a fully stochastic path (LPSMALA) based on a Metropolis-adjusted Langevin algorithm (LPSMALA). Talking about efficiency, routines for Laplace approximations and B-splines evaluations have been coded in C++ and integrated in R via the &lt;a href=&#34;https://www.rcpp.org/&#34;&gt;Rcpp package&lt;/a&gt;, so that the underlying algorithm can be executed in negligible time.&lt;/p&gt;
&lt;p&gt;Below, we provide a short example of how to use the EpiLPS routines to estimate &lt;span class=&#34;math inline&#34;&gt;\(\mathcal{R}_t\)&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;getting-started&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Getting started&lt;/h1&gt;
&lt;p&gt;The EpiLPS package is available from CRAN (see &lt;a href=&#34;https://cran.r-project.org/web/packages/EpiLPS/index.html&#34; class=&#34;uri&#34;&gt;https://cran.r-project.org/web/packages/EpiLPS/index.html&lt;/a&gt;) and can be installed from the R console by typing:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;install.packages(&amp;quot;EpiLPS&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The package can then be loaded as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(&amp;quot;EpiLPS&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The EpiLPS package structure is fairly simple as it consists in a few routines:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The function &lt;code&gt;epilps()&lt;/code&gt; is the core routine for fitting the reproduction number.&lt;/li&gt;
&lt;li&gt;With &lt;code&gt;plot.epilps()&lt;/code&gt;, the user can plot the estimated epidemic curve and &lt;span class=&#34;math inline&#34;&gt;\(\mathcal{R}_t\)&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;Finally, two ancillary routines, &lt;code&gt;episim()&lt;/code&gt; and &lt;code&gt;perfcheck()&lt;/code&gt; have been developed to essentially reproduce the simulation results of the associated paper.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;a-simulated-example&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;A simulated example&lt;/h1&gt;
&lt;p&gt;A set of epidemic data can be simulated with the &lt;code&gt;episim()&lt;/code&gt; routine by specifying a serial interval distribution and by choosing among a set of available patterns for the true reproduction number curve (here we choose pattern number 5 corresponding to a rather wiggly curve).&lt;/p&gt;
&lt;p&gt;The simulated outbreak is for a duration of 40 days as specified in the &lt;code&gt;endepi&lt;/code&gt; option. By setting the option &lt;code&gt;plotsim = TRUE&lt;/code&gt;, the routine returns a figure summarizing the incidence time series, a bar plot for the specified serial interval distribution and the true underlying reproduction number curve.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(1234)

SI &amp;lt;- c(0.344, 0.316, 0.168, 0.104, 0.068)
simepidemic &amp;lt;- episim(
  serial_interval = SI,
  Rpattern = 5,
  plotsim = TRUE,
  verbose = TRUE,
  endepi = 40
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Chosen scenario: 5 &amp;#39;Wiggly then stable Rt&amp;#39;.
## Incidence of cases generated from a Poisson distribution. 
## Total number of days of epidemic: 40.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/paper-epilps-a-fast-and-flexible-bayesian-tool-for-estimation-of-the-time-varying-reproduction-number/index_files/figure-html/Simul-1-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;If you want to have an overview of the generated incidence time series, just type:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;simepidemic$y&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1]  10   6  15  24  37  43  54  46  47  28  20   8  10  10   3   5   3   4   6
## [20]   6  15  21  44  75 135 217 329 409 453 487 457 443 297 290 255 246 246 339
## [39] 395 573&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;smoothing-the-epidemic-curve-and-estimating-mathcalr_t&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Smoothing the epidemic curve and estimating &lt;span class=&#34;math inline&#34;&gt;\(\mathcal{R}_t\)&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Let us now use the &lt;code&gt;epilps()&lt;/code&gt; routine to smooth the epidemic curve and estimate the reproduction number.&lt;/p&gt;
&lt;p&gt;We will do this through LPSMAP (a fully sampling-free approach) and via LPSMALA (a fully stochastic approach relying on a MCMC algorithm with Langevin dynamics), where we specify a chain of length 10000 and a burn-in of size 4000.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;LPSMAP_fit &amp;lt;- epilps(
  incidence = simepidemic$y,
  serial_interval = SI,
  tictoc = TRUE
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Inference method chosen: LPSMAP. 
## CI for LPSMAP computed via lognormal posterior approx. of Rt.Total number of days: 40. 
## Mean Rt discarding first 7 days: 1.327.
## Mean 95% CI of Rt discarding first 7 days: (1.164,1.527) 
## Elapsed real time (wall clock time): 0.261 seconds.&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;LPSMALA_fit &amp;lt;- epilps(
  incidence = simepidemic$y, serial_interval = SI,
  method = &amp;quot;LPSMALA&amp;quot;, chain_length = 10000, burn = 4000
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Inference method chosen: LPSMALA with chain length 10000 and warmup 4000.
## MCMC acceptance rate: 56.41%. 
## Geweke z-score &amp;lt; 2.33 for:  32 / 33  variables. 
## Total number of days: 40. 
## Mean Rt discarding first 7 days: 1.326.
## Mean 95% CI of Rt discarding first 7 days: (1.117,1.555). 
## Timing of routine not requested.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After execution, each routine prints in the console a brief summary of the method that has been requested by the user.&lt;/p&gt;
&lt;p&gt;For LPSMALA, it summarizes the chain length, the acceptance rate (should be around 56%) and other basic information. As can be seen from the printed output, the mean reproduction number for the simulated epidemic is around 1.33.&lt;/p&gt;
&lt;p&gt;We can now use, say, the &lt;code&gt;LPSMALA_fit&lt;/code&gt; object together with the &lt;code&gt;plot()&lt;/code&gt; routine to obtain the smoothed epidemic curve and the estimated reproduction number (by default the credible interval is at a 5% level of significance but this can be changed by the user).&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;days &amp;lt;- seq(8, 40)

#--- Smoothed epidemic curve
gridExtra::grid.arrange(
  plot(LPSMALA_fit,
    plotout = &amp;quot;epicurve&amp;quot;, incibars = TRUE, themetype = &amp;quot;light&amp;quot;,
    epicol = &amp;quot;darkgreen&amp;quot;, cicol = rgb(0.3, 0.73, 0.3, 0.2),
    epititle = &amp;quot;Smoothed epidemic curve&amp;quot;, titlesize = 13, barwidth = 0.25
  ),

  #--- Estimated reproduction number
  plot(LPSMALA_fit,
    plotout = &amp;quot;rt&amp;quot;, theme = &amp;quot;light&amp;quot;, rtcol = &amp;quot;black&amp;quot;,
    titlesize = 13, Rtitle = &amp;quot;Estimated R (LPSMALA)&amp;quot;
  ),
  nrow = 1, ncol = 2
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/paper-epilps-a-fast-and-flexible-bayesian-tool-for-estimation-of-the-time-varying-reproduction-number/index_files/figure-html/Simul-4-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The figure can be customized in various ways:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Users can specify the theme under &lt;code&gt;themetype&lt;/code&gt;. Available options are &lt;code&gt;gray&lt;/code&gt; (the default), &lt;code&gt;classic&lt;/code&gt;, &lt;code&gt;light&lt;/code&gt; and &lt;code&gt;dark&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Other choices, such as whether or not to show the incidence bars, the color of the credible interval envelope, the color of the smoothed epidemic curve and the estimated reproduction number are also available.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The figure above was generated within the &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;&lt;code&gt;ggplot2&lt;/code&gt; package&lt;/a&gt;, but there is also another way of extracting information directly from the &lt;code&gt;LPSMAP_fit&lt;/code&gt; and &lt;code&gt;LPSMALA_fit&lt;/code&gt; objects. In fact, the estimated reproduction number values and their associated credible interval for each day can be extracted and plotted.&lt;/p&gt;
&lt;p&gt;Below, we make the exercise and plot the estimated &lt;span class=&#34;math inline&#34;&gt;\(\mathcal{R}_t\)&lt;/span&gt; obtained with LPSMAP and LPSMALA, respectively and compare it with the true underlying reproduction number curve. The fit is quite good.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;par(mfrow = c(1, 2))

#--- LPSMAP vs target R
plot(days, sapply(days, simepidemic$Rtrue),
  type = &amp;quot;l&amp;quot;, lwd = 2, ylim = c(0, 4),
  ylab = &amp;quot;Estimated R&amp;quot;, xlab = &amp;quot;Time&amp;quot;
)
polygon(
  x = c(days, rev(days)), y = c(
    LPSMAP_fit$epifit$R95CI_low[8:40],
    rev(LPSMAP_fit$epifit$R95CI_up[8:40])
  ),
  col = rgb(0.23, 0.54, 1, 0.3), border = NA
)
lines(days, LPSMAP_fit$epifit$R_estim[8:40], type = &amp;quot;l&amp;quot;, col = &amp;quot;cornflowerblue&amp;quot;, lwd = 2)
lines(days, sapply(days, simepidemic$Rtrue), type = &amp;quot;l&amp;quot;, lwd = 2)

grid(nx = 10, ny = 10)
legend(&amp;quot;topright&amp;quot;,
  lty = c(1, 1), lwd = c(2, 2),
  col = c(&amp;quot;black&amp;quot;, &amp;quot;blue&amp;quot;, rgb(0.23, 0.54, 1, 0.3)),
  c(&amp;quot;Target R&amp;quot;, &amp;quot;LPSMAP&amp;quot;, &amp;quot;LPSMAP 95% CI&amp;quot;), bty = &amp;quot;n&amp;quot;, cex = 0.9
)

#--- LPSMALA vs target R
plot(days, sapply(days, simepidemic$Rtrue),
  type = &amp;quot;l&amp;quot;, lwd = 2, ylim = c(0, 4),
  ylab = &amp;quot;Estimated R&amp;quot;, xlab = &amp;quot;Time&amp;quot;
)
polygon(
  x = c(days, rev(days)), y = c(
    LPSMALA_fit$epifit$R95CI_low[8:40],
    rev(LPSMALA_fit$epifit$R95CI_up[8:40])
  ),
  col = rgb(1, 0.23, 0.31, 0.3), border = NA
)
lines(days, LPSMALA_fit$epifit$R_estim[8:40], type = &amp;quot;l&amp;quot;, col = &amp;quot;red&amp;quot;, lwd = 2)
lines(days, sapply(days, simepidemic$Rtrue), type = &amp;quot;l&amp;quot;, lwd = 2)

grid(nx = 10, ny = 10)
legend(&amp;quot;topright&amp;quot;,
  lty = c(1, 1), lwd = c(2, 2),
  col = c(&amp;quot;black&amp;quot;, &amp;quot;red&amp;quot;, rgb(1, 0.23, 0.31, 0.3)),
  c(&amp;quot;Target R&amp;quot;, &amp;quot;LPSMALA&amp;quot;, &amp;quot;LPSMALA 95% CI&amp;quot;), bty = &amp;quot;n&amp;quot;, cex = 0.9
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/paper-epilps-a-fast-and-flexible-bayesian-tool-for-estimation-of-the-time-varying-reproduction-number/index_files/figure-html/Simul-5-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;You can access, say, the results of the last week of the epidemic by typing:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Estimated R of the last week (with LPSMAP)
round(tail(LPSMAP_fit$epifit[, 1:4], 7), 3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    Date R_estim R95CI_low R95CI_up
## 34   34   0.708     0.663    0.756
## 35   35   0.724     0.676    0.775
## 36   36   0.809     0.755    0.868
## 37   37   0.971     0.908    1.039
## 38   38   1.205     1.135    1.279
## 39   39   1.461     1.384    1.541
## 40   40   1.671     1.557    1.794&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Estimated mean number of cases of the last week (with LPSMAP)
round(tail(LPSMAP_fit$epifit[, 5:7], 7))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    mu_estim mu95CI_low mu95CI_up
## 34      284        225       357
## 35      254        202       319
## 36      248        196       312
## 37      267        211       338
## 38      319        253       404
## 39      411        325       520
## 40      552        394       774&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;usa-hospitalization-data&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;USA hospitalization data&lt;/h1&gt;
&lt;p&gt;To illustrate EpiLPS on real data, we download hospitalization data from the &lt;code&gt;COVID19&lt;/code&gt; package for the USA in the period ranging from 2021-09-01 to 2022-09-01 and apply the &lt;code&gt;epilps()&lt;/code&gt; routine to estimate the reproduction number.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;install.packages(&amp;quot;COVID19&amp;quot;)
library(&amp;quot;COVID19&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Get data and specify serial interval distribution
USADat &amp;lt;- COVID19::covid19(
  country = &amp;quot;US&amp;quot;, level = 1, start = &amp;quot;2021-09-01&amp;quot;,
  end = &amp;quot;2022-09-01&amp;quot;, verbose = FALSE
)

si &amp;lt;- c(0.344, 0.316, 0.168, 0.104, 0.068)

inciUSA &amp;lt;- USADat$hosp
dateUSA &amp;lt;- USADat$date&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We use the &lt;code&gt;epilps()&lt;/code&gt; routine with method LPSMAP (default) and plot the smoothed epidemic curve and the estimated reproduction number with a 95% credible interval.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;epifit &amp;lt;- epilps(incidence = inciUSA, serial_interval = si, K = 20)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Inference method chosen: LPSMAP. 
## CI for LPSMAP computed via lognormal posterior approx. of Rt.Total number of days: 366. 
## Mean Rt discarding first 7 days: 0.994.
## Mean 95% CI of Rt discarding first 7 days: (0.983,1.005) 
## Timing of routine not requested.&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;gridExtra::grid.arrange(
  plot(epifit,
    dates = dateUSA, datelab = &amp;quot;3m&amp;quot;,
    plotout = &amp;quot;epicurve&amp;quot;, incibars = FALSE, themetype = &amp;quot;light&amp;quot;,
    epicol = &amp;quot;darkgreen&amp;quot;, cicol = rgb(0.3, 0.73, 0.3, 0.2),
    epititle = &amp;quot;USA smoothed epidemic curve&amp;quot;, titlesize = 13
  ),
  plot(epifit,
    dates = dateUSA, datelab = &amp;quot;3m&amp;quot;,
    plotout = &amp;quot;rt&amp;quot;, theme = &amp;quot;light&amp;quot;, rtcol = &amp;quot;black&amp;quot;,
    titlesize = 13, Rtitle = &amp;quot;USA Estimated R&amp;quot;
  ),
  nrow = 1, ncol = 2
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/paper-epilps-a-fast-and-flexible-bayesian-tool-for-estimation-of-the-time-varying-reproduction-number/index_files/figure-html/USA-2-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope you will find the method developed in the paper as useful as I do. Feel free to reach out to me and to the authors if you happen to use it for your own research.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-cori2013new&#34; class=&#34;csl-entry&#34;&gt;
Cori, Anne, Neil M Ferguson, Christophe Fraser, and Simon Cauchemez. 2013. &lt;span&gt;“A New Framework and Software to Estimate Time-Varying Reproduction Numbers During Epidemics.”&lt;/span&gt; &lt;em&gt;American Journal of Epidemiology&lt;/em&gt; 178 (9): 1505–12.
&lt;/div&gt;
&lt;div id=&#34;ref-gressani2022epilps&#34; class=&#34;csl-entry&#34;&gt;
Gressani, Oswaldo, Jacco Wallinga, Christian L Althaus, Niel Hens, and Christel Faes. 2022. &lt;span&gt;“EpiLPS: A Fast and Flexible Bayesian Tool for Estimation of the Time-Varying Reproduction Number.”&lt;/span&gt; &lt;em&gt;PLoS Computational Biology&lt;/em&gt; 18 (10): e1010618. &lt;a href=&#34;https://doi.org/10.1371/journal.pcbi.1010618&#34;&gt;https://doi.org/10.1371/journal.pcbi.1010618&lt;/a&gt;.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>One-sample Wilcoxon test in R</title>
      <link>https://statsandr.com/blog/one-sample-wilcoxon-test-in-r/</link>
      <pubDate>Thu, 07 Jul 2022 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/one-sample-wilcoxon-test-in-r/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#when&#34; id=&#34;toc-when&#34;&gt;When?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#data&#34; id=&#34;toc-data&#34;&gt;Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#how&#34; id=&#34;toc-how&#34;&gt;How?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#combine-statistical-test-and-plot&#34; id=&#34;toc-combine-statistical-test-and-plot&#34;&gt;Combine statistical test and plot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;images/one-sample-wilcoxon-test-in-r.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;In a previous article, we showed how to do a &lt;a href=&#34;https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/&#34;&gt;two-sample Wilcoxon test&lt;/a&gt; in R. Remember that there are actually two versions of this test:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;The &lt;strong&gt;Mann-Whitney-Wilcoxon test&lt;/strong&gt; (also referred as Wilcoxon rank sum test or Mann-Whitney U test), used to compare two &lt;strong&gt;independent&lt;/strong&gt; samples. This test is the non-parametric version of the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test for independent samples&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;Wilcoxon signed-rank test&lt;/strong&gt; (also referred as Wilcoxon test for paired samples), used to compare two paired samples. This test is the non-parametric version of the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test for paired samples&lt;/a&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In another article, we also showed how to do a &lt;a href=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r-test-on-one-mean/&#34;&gt;one-sample t-test&lt;/a&gt; by hand and in R. This test is used to determine whether the mean of a measurement variable is different from a specified value (a value that you specify based on your beliefs or a theoretical expectation for example). Since it is a parametric test, the data should follow a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution&lt;/a&gt; (or sample size should be large enough (i.e., above 30), thanks to the central limit theorem) for the results to be valid.&lt;/p&gt;
&lt;p&gt;Unlike the one-sample t-test, the &lt;strong&gt;one-sample Wilcoxon test&lt;/strong&gt; (also referred as the one-sample Wilcoxon signed-rank test) is a non-parametric test, meaning that it does not rely on data belonging to any particular parametric family of probability distributions. Non-parametric tests usually have the same goal as their parametric counterparts (in this case, compare data to a given value). Nonetheless, they do not require the assumption of normality and they can deal with &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt; and Likert scales.&lt;/p&gt;
&lt;p&gt;In this article, we show when to perform the one-sample Wilcoxon test, how to do it in R and how to interpret its results. We will also briefly show some appropriate visualizations.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;when&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;When?&lt;/h1&gt;
&lt;p&gt;The &lt;strong&gt;one-sample Wilcoxon test is used to compare our observations to a given default value&lt;/strong&gt;—a value that you specify based on your beliefs or a theoretical expectation for example. In other words, it is used to determine if a group is significantly different from a known or hypothesized population value on the variable of interest.&lt;/p&gt;
&lt;p&gt;Since the test statistic is computed based on the ranks of the difference between the observed values and the default value (making it a non-parametric test), the one-sample Wilcoxon test is more appropriate than a one-sample t-test when the observations do not follow a normal distribution.&lt;/p&gt;
&lt;p&gt;The goal of this test is to verify whether the observations are significantly different from our default value. In terms of null and alternative hypotheses, we have (for a two-tailed test):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0:\)&lt;/span&gt; location of the data is &lt;em&gt;equal&lt;/em&gt; to the chosen value&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1:\)&lt;/span&gt; location of the data is &lt;em&gt;different&lt;/em&gt; from the chosen value&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In other words, a significant result (i.e., a rejection of the null hypothesis) suggests that the location of the data is &lt;em&gt;different&lt;/em&gt; from the chosen value.&lt;/p&gt;
&lt;p&gt;Note that some authors suggest that this test is a test of the median, that is (for a two-tailed test):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0:\)&lt;/span&gt; the median is &lt;em&gt;equal&lt;/em&gt; to the chosen value&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1:\)&lt;/span&gt; the median is &lt;em&gt;different&lt;/em&gt; from the chosen value&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;However, this is the case only if the data are symmetric. Without further assumptions about the distribution of the data, the one-sample Wilcoxon test is not a test of the median but a test about the location of the data.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Note that although the normality assumption is not required, the independence assumption must still be verified. This means that observations must be independent of one another (usually, random sampling is sufficient to have independence).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;data&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Data&lt;/h1&gt;
&lt;p&gt;For our illustration, suppose we want to test whether the scores at an exam differ from 10, that is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0:\)&lt;/span&gt; scores at the exam &lt;span class=&#34;math inline&#34;&gt;\(= 10\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1:\)&lt;/span&gt; scores at the exam &lt;span class=&#34;math inline&#34;&gt;\(\ne 10\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;To verify this, we have a sample of 15 students and their score at the exam:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    Student_ID Score
## 1           1    17
## 2           2     5
## 3           3     1
## 4           4    10
## 5           5     4
## 6           6    18
## 7           7    17
## 8           8    15
## 9           9     7
## 10         10     4
## 11         11     5
## 12         12    14
## 13         13    20
## 14         14    18
## 15         15    15&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Scores between students are assumed to be independent (a student’s score is not impacted or influenced by the score of another student). Therefore, the independence assumption is met.&lt;/p&gt;
&lt;p&gt;Moreover, sample size is small (n &amp;lt; 30) and based on the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt; the data do not follow a normal distribution:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# histogram
hist(dat$Score)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/one-sample-wilcoxon-test-in-r/index_files/figure-html/unnamed-chunk-3-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Note that we refrain from verifying the normality via a normality test (such as the &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#normality-test&#34;&gt;Shapiro-Wilk test&lt;/a&gt; for instance) because for small sample sizes, normality tests have little power to reject the null hypothesis and therefore small samples most often pass normality tests &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-oztuna2006investigation&#34;&gt;Öztuna et al. 2006&lt;/a&gt;; &lt;a href=&#34;#ref-ghasemi2012normality&#34;&gt;Ghasemi and Zahediasl 2012&lt;/a&gt;)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Note also that although we use a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#quantitative&#34;&gt;quantitative variable&lt;/a&gt; for the illustration, the one-sample Wilcoxon test is also appropriate for interval data and Likert scales.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;how&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How?&lt;/h1&gt;
&lt;p&gt;The one-sample Wilcoxon test can be done in R with the &lt;code&gt;wilcox.test()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;But first, it is a good practice to visualize our data in a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#boxplot&#34;&gt;boxplot&lt;/a&gt; and compute some &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt; to compare our observations with our default value:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# boxplot
boxplot(dat$Score,
  ylab = &amp;quot;Score&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/one-sample-wilcoxon-test-in-r/index_files/figure-html/unnamed-chunk-4-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;If like me you prefer to use the &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;&lt;code&gt;{ggplot2}&lt;/code&gt; package&lt;/a&gt; for your plots:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# boxplot
library(ggplot2)

ggplot(dat, aes(y = Score)) +
  geom_boxplot() +
  labs(y = &amp;quot;Score&amp;quot;) +
  theme( # remove axis text and ticks
    axis.text.x = element_blank(),
    axis.ticks = element_blank()
  )&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/one-sample-wilcoxon-test-in-r/index_files/figure-html/unnamed-chunk-5-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Some basic descriptive statistics (rounded to two decimals):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;round(summary(dat$Score),
  digits = 2
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##    1.00    5.00   14.00   11.33   17.00   20.00&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From the boxplot and the descriptive statistics above, we see that the mean and median of the scores in our sample are respectively 11.33 and 14.&lt;/p&gt;
&lt;p&gt;The one-sample Wilcoxon test will tell us whether the scores are &lt;em&gt;significantly&lt;/em&gt; different from 10 or not (and thus whether they are different from 10 in the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;population&lt;/a&gt; or not):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;wilcox.test(dat$Score,
  mu = 10 # default value
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Wilcoxon signed rank test with continuity correction
## 
## data:  dat$Score
## V = 67, p-value = 0.3779
## alternative hypothesis: true location is not equal to 10&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output presents several information such as the:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;title of the test&lt;/li&gt;
&lt;li&gt;data&lt;/li&gt;
&lt;li&gt;test statistic&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value&lt;/li&gt;
&lt;li&gt;alternative hypothesis&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We focus on the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value to interpret and conclude the test.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Interpretation:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Based on the results of the test, (at the significance level of 0.05) we do not reject the null hypothesis, so we do not reject the hypothesis that the scores at this exam are equal to 10, and we cannot conclude that the scores are significantly different from 10 (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.378).&lt;/p&gt;
&lt;p&gt;By default, it is a two-tailed test that is done. As for the &lt;code&gt;t.test()&lt;/code&gt; function, we can specify that a one-sided test is required by using either the &lt;code&gt;alternative = &#34;greater&#34;&lt;/code&gt; or &lt;code&gt;alternative = &#34;less&lt;/code&gt; argument in the &lt;code&gt;wilcox.test()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;For example, if we want to test that the scores are &lt;em&gt;higher&lt;/em&gt; than 10:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;wilcox.test(dat$Score,
  mu = 10, # default value
  alternative = &amp;quot;greater&amp;quot; # H1: scores &amp;gt; 10
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Wilcoxon signed rank test with continuity correction
## 
## data:  dat$Score
## V = 67, p-value = 0.189
## alternative hypothesis: true location is greater than 10&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Interpretation:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In this case, we still do not reject the hypothesis that scores are equal to 10 and we cannot conclude that scores are significantly higher than 10 (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.189).&lt;/p&gt;
&lt;p&gt;For more information about the arguments available in the function, see &lt;code&gt;?wilcox.test&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Note that you may encounter the following warnings when using &lt;code&gt;wilcox.test()&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Warning messages:
1: In wilcox.test.default(dat$Score, mu = 10) :
  cannot compute exact p-value with ties
2: In wilcox.test.default(dat$Score, mu = 10) :
  cannot compute exact p-value with zeroes&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is a warning rather than an indication that your results are incorrect. R is informing you that it is reporting a &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value based on a normal approximation rather than an exact &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value based on the data because there are ties (some values are the same). Use the &lt;code&gt;exact = FALSE&lt;/code&gt; option if you want to remove the warning.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;combine-statistical-test-and-plot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Combine statistical test and plot&lt;/h1&gt;
&lt;p&gt;If you are a frequent user of the blog, you know that I like to present results of a test directly on a plot. This allows me to visualize the data and conclude the test in a concise manner.&lt;/p&gt;
&lt;p&gt;This is possible thanks to the &lt;code&gt;gghistostats()&lt;/code&gt; function within the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load package
library(ggstatsplot)

# combine plot and test
gghistostats(
  data = dat, # dataframe
  x = Score, # variable
  type = &amp;quot;nonparametric&amp;quot;, # nonparametric = Wilcoxon, parametric = t-test
  test.value = 10 # default value
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/one-sample-wilcoxon-test-in-r/index_files/figure-html/unnamed-chunk-9-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The histogram&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt; shows the distribution of the scores and results of the test is shown in the title of the plot.&lt;/p&gt;
&lt;p&gt;As you can see, results of the test are the same, that is, there is not enough evidence in the data to conclude that scores are significantly different from 10 (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.378).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to understand the one-sample Wilcoxon test and how to do it in R.&lt;/p&gt;
&lt;p&gt;As always, if you have any question related to the topic covered in this paper, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-ghasemi2012normality&#34; class=&#34;csl-entry&#34;&gt;
Ghasemi, Asghar, and Saleh Zahediasl. 2012. &lt;span&gt;“Normality Tests for Statistical Analysis: A Guide for Non-Statisticians.”&lt;/span&gt; &lt;em&gt;International Journal of Endocrinology and Metabolism&lt;/em&gt; 10 (2): 486.
&lt;/div&gt;
&lt;div id=&#34;ref-oztuna2006investigation&#34; class=&#34;csl-entry&#34;&gt;
Öztuna, Derya, Atilla Halil Elhan, and Ersöz Tüccar. 2006. &lt;span&gt;“Investigation of Four Different Normality Tests in Terms of Type 1 Error Rate and Power Under Different Distributions.”&lt;/span&gt; &lt;em&gt;Turkish Journal of Medical Sciences&lt;/em&gt; 36 (3): 171–76.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;See more information in this &lt;a href=&#34;https://rcompanion.org/handbook/F_02.html&#34;&gt;article&lt;/a&gt;.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;This histogram looks different than the previous one because the number of bins is different (4 versus 5 bins).&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Koh-Lanta 2022: the ambassadors probability problem</title>
      <link>https://statsandr.com/blog/koh-lanta-2022-ambassadors-probability-problem/</link>
      <pubDate>Mon, 16 May 2022 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/koh-lanta-2022-ambassadors-probability-problem/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#before-2022&#34; id=&#34;toc-before-2022&#34;&gt;Before 2022&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#in-2022&#34; id=&#34;toc-in-2022&#34;&gt;In 2022&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#probabilities-computation-in-r&#34; id=&#34;toc-probabilities-computation-in-r&#34;&gt;Probabilities computation in R&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#first-draw&#34; id=&#34;toc-first-draw&#34;&gt;First draw&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#second-draw&#34; id=&#34;toc-second-draw&#34;&gt;Second draw&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#third-draw&#34; id=&#34;toc-third-draw&#34;&gt;Third draw&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#game-limited-to-3-draws&#34; id=&#34;toc-game-limited-to-3-draws&#34;&gt;Game limited to 3 draws&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#game-limited-to-5-draws&#34; id=&#34;toc-game-limited-to-5-draws&#34;&gt;Game limited to 5 draws&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#game-limited-to-100-draws&#34; id=&#34;toc-game-limited-to-100-draws&#34;&gt;Game limited to 100 draws&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#game-limited-to-the-number-of-necessary-draws&#34; id=&#34;toc-game-limited-to-the-number-of-necessary-draws&#34;&gt;Game limited to the number of necessary draws&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#final-winning-probabilities&#34; id=&#34;toc-final-winning-probabilities&#34;&gt;Final winning probabilities&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#visual-representations&#34; id=&#34;toc-visual-representations&#34;&gt;Visual representations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#coded-into-a-function&#34; id=&#34;toc-coded-into-a-function&#34;&gt;Coded into a function&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;images/koh-lanta-2022-ambassadors-probability-problem.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;There is a popular TV show broadcasted in France and the french-speaking part of Belgium called “&lt;strong&gt;Koh-Lanta&lt;/strong&gt;”.&lt;/p&gt;
&lt;p&gt;In this show, several adventurers are dropped off on a desert island with almost no food nor equipment (just a personal backpack with their clothes and a small portion of rice). They must learn to survive on the hostile island by building their hut, finding water and food, etc.&lt;/p&gt;
&lt;p&gt;Each season, adventurers are divided into teams (called tribes), and the teams compete against each other in games involving ability, strength, thinking and endurance. Every other game, the winning tribe receives some food or survival equipment (something to fish or something to make a fire, for instance). The losing tribe receives nothing. For the other half of the games, each member of the losing tribe has to elect an adventurer. The adventurer with the most votes leaves the show definitely. The winning tribe goes back to its island with all of its members.&lt;/p&gt;
&lt;p&gt;At some point during the show, the two competing tribes are grouped together into one single tribe, and it continues this time with each adventurer competing against each other (so they play individually). The winner of the show is the last one to “survive”.&lt;/p&gt;
&lt;p&gt;The 2022 season started with 24 adventurers. Just before being grouped together, each tribe has to select an adventurer in the opposing tribe. The two selected adventurers become ambassadors of their tribe. The two ambassadors must then go to another island in order to choose the adventurer who is going to leaves the show definitely. The adventurer selected by the two ambassadors will not be part of the reunification of the two tribes and her adventure stops there.&lt;/p&gt;
&lt;p&gt;Of course, both ambassadors want to eliminate a member of the opposing tribe (to arrive at the reunification with the most allies). If the two ambassadors cannot agree, they have to play a game that will determine which of the 2 ambassadors must leave the show. This game is entirely based on luck. For the rest of the article, we call this game the &lt;em&gt;ambassadors’ game&lt;/em&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;before-2022&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Before 2022&lt;/h1&gt;
&lt;p&gt;Here were the rules of the ambassadors’ game &lt;em&gt;before&lt;/em&gt; the 2022 season:&lt;/p&gt;
&lt;p&gt;There are two identical urns, one in front of each ambassador. Each urn contains exactly &lt;strong&gt;one black ball&lt;/strong&gt; and &lt;strong&gt;one white ball&lt;/strong&gt;. Each ambassador has to draw a ball among the 2 from his urn. Both urns are of course closed, so no one sees which ball is picked (nor which one is not picked). The winner of the game (remember that the winner stays in the show, the loser has to leave definitely) is the one who picks a white ball while the other ambassador draws a black ball. If both ambassadors draw the same ball (both black or both white), the balls are put back in the urns and the game start over (with the exact same conditions) until the two ambassadors draw a ball of different color.&lt;/p&gt;
&lt;p&gt;For each draw, there are thus four possible results:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Ambassador from tribe A draws a white ball and ambassador from tribe B draws a black ball: ambassador from tribe A wins.&lt;/li&gt;
&lt;li&gt;Ambassador from tribe A draws a black ball and ambassador from tribe B draws a white ball: ambassador from tribe B wins.&lt;/li&gt;
&lt;li&gt;Both ambassadors draw a black ball: the game start over.&lt;/li&gt;
&lt;li&gt;Both ambassadors draw a white ball: the game start over.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Let’s compute the probability for each result to occur. Since the two events are &lt;a href=&#34;https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/#independence-of-two-events&#34;&gt;independent&lt;/a&gt; (the fact that ambassador A draws a white ball does not change the probability for ambassador B to draw a white ball makes the two events independent), we can multiply the probabilities to compute the joint probability of the two events.&lt;/p&gt;
&lt;p&gt;With &lt;span class=&#34;math inline&#34;&gt;\(P_A\)&lt;/span&gt; (&lt;span class=&#34;math inline&#34;&gt;\(P_B\)&lt;/span&gt;) denoting the probability that ambassador from tribe A (B) draws a white ball, we have:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(P_A \cdot (1 - P_B) = 0.5 \cdot 0.5 = 0.25\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\((1 - P_A) \cdot P_B = 0.5 \cdot 0.5 = 0.25\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\((1 - P_A) \cdot (1 - P_B) = 0.5 \cdot 0.5 = 0.25\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(P_A \cdot P_B = 0.5 \cdot 0.5 = 0.25\)&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The sum of the 4 probabilities gives 1 (i.e., 100%), which makes sense since it covers all possible outcomes.&lt;/p&gt;
&lt;p&gt;This means that, &lt;em&gt;on the first draw&lt;/em&gt;, each ambassador has a probability of 25% to win the game (outcome 1 for ambassador A, outcome 2 for ambassador B).&lt;/p&gt;
&lt;p&gt;Of course, since the game is repeated until there is a winner, probabilities for outcomes 3 and 4 tend, in the long run, to decrease until it becomes null (0%). If this statement is not straightforward to you, think about it like this: if you play that game with your friend up to 100 times, what is the probability that there is still no winner, meaning that you and your friend drew the same ball (never a different color) 100 times in a row. You conceive that it is highly unlikely.&lt;/p&gt;
&lt;p&gt;In this context, since both urns are identical and the game is played indefinitely until there is a winner, ambassadors have exactly the same probability of winning that game. It is indeed a 50-50 chance for each of them.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-2022&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;In 2022&lt;/h1&gt;
&lt;p&gt;Of course, I would not write an article about that ambassadors’ game if it is was this easy and straightforward.&lt;/p&gt;
&lt;p&gt;The 2022 season differs from the previous ones in the sense that for each game, the losing tribe receives an additional punishment (called a curse in the show). As a consequence, this year, the two urns at the ambassadors’ game were &lt;strong&gt;not&lt;/strong&gt; identical.&lt;/p&gt;
&lt;p&gt;To give you some context, the red tribe won against the yellow tribe in the last game before the ambassadors’ negotiation. The punishment for the yellow tribe was the following:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The yellow tribe (with its ambassador Colin) had an urn with &lt;strong&gt;2 black balls&lt;/strong&gt; and 1 white ball.&lt;/li&gt;
&lt;li&gt;The red tribe (with its ambassador Louana) had an urn with &lt;strong&gt;1 black ball&lt;/strong&gt; and 1 white ball.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This is indeed a punishment for the yellow tribe since the game is not fair anymore: the ambassador of the red tribe clearly has a higher chance of winning that game compared to the ambassador of the yellow tribe.&lt;/p&gt;
&lt;p&gt;For the curious among you, here is how it happened:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The two ambassadors were informed by the presenter Denis Brogniart about the composition of the urns for each tribe.&lt;/li&gt;
&lt;li&gt;Knowing that the odds were not in his favour, Colin (ambassador of the yellow tribe), chose not to play the game.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;They finally agreed on the name of the adventurer who would leave the show (an adventurer of the yellow tribe).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You guessed it by now, the reason for writing this article is of course not to explain you what actually happened—the news sites do it better and much faster than me. The reason is that I wanted to compute the chance of winning the game for each ambassador if they had not agreed on an adventurer to eliminate.&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Moreover, I wanted to compute these probabilities in R through simulation. And why not, reuse the code in case organizers of Koh-Lanta decide to change the rules again in the future.&lt;/p&gt;
&lt;p&gt;Even if you do not watch Koh-Lanta (because it is not broadcasted in your country, or you do not like the show), it could be of interest to those of you who want to see:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;how a real life example can be transferred into R,&lt;/li&gt;
&lt;li&gt;and how a &lt;code&gt;for loop&lt;/code&gt; and a function can be used to answer the initial question.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;probabilities-computation-in-r&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Probabilities computation in R&lt;/h1&gt;
&lt;p&gt;For the remaining of this article, we denote:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(p_c\)&lt;/span&gt;, the probability that Colin (ambassador of the yellow tribe) draws a white ball,&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(p_l\)&lt;/span&gt;, the probability that Louana (ambassador of the red tribe) draws a white ball,&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(q_c\)&lt;/span&gt;, the probability that Colin draws a black ball,&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(q_l\)&lt;/span&gt;, the probability that Louana draws a black ball.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Based on the composition of the urns given by Denis Brogniart, we have:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;p_c &amp;lt;- 1 / 3
p_l &amp;lt;- 1 / 2
q_c &amp;lt;- (1 - p_c)
q_l &amp;lt;- (1 - p_l)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;first-draw&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;First draw&lt;/h2&gt;
&lt;p&gt;To start easy, let’s first compute the winning probabilities for each ambassador &lt;em&gt;on the first draw only&lt;/em&gt;. Remember that to have a winner, balls must be of different colors.&lt;/p&gt;
&lt;p&gt;Louana wins if and only if Colin draws a black ball and Louana draws a white ball:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Louana winning on first draw
l_win &amp;lt;- q_c * p_l
l_win&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.3333333&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Louana has a 33.33% chance of winning on the first draw.&lt;/p&gt;
&lt;p&gt;On the other hand, Colin wins if and only if Louana draws a black ball and Colin draws a white ball:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Colin winning on first draw
c_win &amp;lt;- q_l * p_c
c_win&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.1666667&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Colin has a 16.67% chance of winning on the first draw.&lt;/p&gt;
&lt;p&gt;You can already see that the game is in favour of Louana, as expected. Let’s see now how it evolves when playing several times.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;second-draw&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Second draw&lt;/h2&gt;
&lt;p&gt;To win exactly on the second draw, it must be a tie on the first draw.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Louana winning on second draw
tie &amp;lt;- (p_c * p_l) + (q_c * q_l)

l_win2 &amp;lt;- tie * l_win
l_win2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.1666667&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Colin winning on second draw
c_win2 &amp;lt;- tie * c_win
c_win2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.08333333&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;Louana has a 16.67% chance of winning on the second draw.&lt;/li&gt;
&lt;li&gt;Colin has a 8.33% chance of winning on the second draw.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;third-draw&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Third draw&lt;/h2&gt;
&lt;p&gt;To win exactly on the third draw, it must be a tie on the first two draws.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Louana winning on third draw
l_win3 &amp;lt;- (tie^2) * l_win
l_win3&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.08333333&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Colin winning on third draw
c_win3 &amp;lt;- (tie^2) * c_win
c_win3&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.04166667&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;Louana has a 8.33% chance of winning on the third draw.&lt;/li&gt;
&lt;li&gt;Colin has a 4.17% chance of winning on the third draw.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A pattern seems to emerge in the code.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;game-limited-to-3-draws&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Game limited to 3 draws&lt;/h2&gt;
&lt;p&gt;We can already compute the probabilities of winning for each ambassador as if the game was limited to three draws, by summing the probabilities for each of the first three draws:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Louana winning on draw 1, 2 or 3
l_win_tot &amp;lt;- l_win + l_win2 + l_win3
l_win_tot&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.5833333&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Colin winning on draw 1, 2 or 3
c_win_tot &amp;lt;- c_win + c_win2 + c_win3
c_win_tot&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.2916667&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;Louana has a 58.33% chance of winning if the game is limited to three draws.&lt;/li&gt;
&lt;li&gt;Colin has a 29.17% chance of winning if the game is limited to three draws.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;game-limited-to-5-draws&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Game limited to 5 draws&lt;/h2&gt;
&lt;p&gt;Now if we compute the probabilities as if the game was limited to 5 draws and generalize the computation to see the pattern even more clearly, we have:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Louana winning
l_win_tot &amp;lt;- ((tie^0) * l_win) +
  ((tie^1) * l_win) +
  ((tie^2) * l_win) +
  ((tie^3) * l_win) +
  ((tie^4) * l_win)

l_win_tot&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.6458333&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Colin winning
c_win_tot &amp;lt;- ((tie^0) * c_win) +
  ((tie^1) * c_win) +
  ((tie^2) * c_win) +
  ((tie^3) * c_win) +
  ((tie^4) * c_win)

c_win_tot&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.3229167&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;Louana has a 64.58% chance of winning if the game is limited to 5 draws.&lt;/li&gt;
&lt;li&gt;Colin has a 32.29% chance of winning if the game is limited to 5 draws.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;game-limited-to-100-draws&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Game limited to 100 draws&lt;/h2&gt;
&lt;p&gt;We could continue like this for a long time, but for now let’s compute it for up to 100 draws, using a &lt;code&gt;for loop&lt;/code&gt;. Using a &lt;code&gt;for loop&lt;/code&gt; is necessary here in order to avoid to copy-paste our computations a hundred times.&lt;/p&gt;
&lt;p&gt;For the ease of illustration, we compute only the probability of winning for Louana. We will show later on how the probability for Colin can easily be computed.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;n_draws &amp;lt;- 100 # number of draws
l_win_tot &amp;lt;- c() # set empty vector

for (i in 1:n_draws) {
  l_win_tot[i] &amp;lt;- ((tie^(i - 1)) * l_win) # prob of Louana winning up to n_draws
  print(paste0(&amp;quot;Draw &amp;quot;, i, &amp;quot;: &amp;quot;, sum(l_win_tot))) # print sum of winning up to n_draws
}&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;Draw 1: 0.333333333333333&amp;quot;
## [1] &amp;quot;Draw 2: 0.5&amp;quot;
## [1] &amp;quot;Draw 3: 0.583333333333333&amp;quot;
## [1] &amp;quot;Draw 4: 0.625&amp;quot;
## [1] &amp;quot;Draw 5: 0.645833333333333&amp;quot;
## [1] &amp;quot;Draw 6: 0.65625&amp;quot;
## [1] &amp;quot;Draw 7: 0.661458333333333&amp;quot;
## [1] &amp;quot;Draw 8: 0.6640625&amp;quot;
## [1] &amp;quot;Draw 9: 0.665364583333333&amp;quot;
## [1] &amp;quot;Draw 10: 0.666015625&amp;quot;
## [1] &amp;quot;Draw 11: 0.666341145833333&amp;quot;
## [1] &amp;quot;Draw 12: 0.66650390625&amp;quot;
## [1] &amp;quot;Draw 13: 0.666585286458333&amp;quot;
## [1] &amp;quot;Draw 14: 0.6666259765625&amp;quot;
## [1] &amp;quot;Draw 15: 0.666646321614583&amp;quot;
## [1] &amp;quot;Draw 16: 0.666656494140625&amp;quot;
## [1] &amp;quot;Draw 17: 0.666661580403646&amp;quot;
## [1] &amp;quot;Draw 18: 0.666664123535156&amp;quot;
## [1] &amp;quot;Draw 19: 0.666665395100911&amp;quot;
## [1] &amp;quot;Draw 20: 0.666666030883789&amp;quot;
## [1] &amp;quot;Draw 21: 0.666666348775228&amp;quot;
## [1] &amp;quot;Draw 22: 0.666666507720947&amp;quot;
## [1] &amp;quot;Draw 23: 0.666666587193807&amp;quot;
## [1] &amp;quot;Draw 24: 0.666666626930237&amp;quot;
## [1] &amp;quot;Draw 25: 0.666666646798452&amp;quot;
## [1] &amp;quot;Draw 26: 0.666666656732559&amp;quot;
## [1] &amp;quot;Draw 27: 0.666666661699613&amp;quot;
## [1] &amp;quot;Draw 28: 0.66666666418314&amp;quot;
## [1] &amp;quot;Draw 29: 0.666666665424903&amp;quot;
## [1] &amp;quot;Draw 30: 0.666666666045785&amp;quot;
## [1] &amp;quot;Draw 31: 0.666666666356226&amp;quot;
## [1] &amp;quot;Draw 32: 0.666666666511446&amp;quot;
## [1] &amp;quot;Draw 33: 0.666666666589056&amp;quot;
## [1] &amp;quot;Draw 34: 0.666666666627862&amp;quot;
## [1] &amp;quot;Draw 35: 0.666666666647264&amp;quot;
## [1] &amp;quot;Draw 36: 0.666666666656965&amp;quot;
## [1] &amp;quot;Draw 37: 0.666666666661816&amp;quot;
## [1] &amp;quot;Draw 38: 0.666666666664241&amp;quot;
## [1] &amp;quot;Draw 39: 0.666666666665454&amp;quot;
## [1] &amp;quot;Draw 40: 0.66666666666606&amp;quot;
## [1] &amp;quot;Draw 41: 0.666666666666364&amp;quot;
## [1] &amp;quot;Draw 42: 0.666666666666515&amp;quot;
## [1] &amp;quot;Draw 43: 0.666666666666591&amp;quot;
## [1] &amp;quot;Draw 44: 0.666666666666629&amp;quot;
## [1] &amp;quot;Draw 45: 0.666666666666648&amp;quot;
## [1] &amp;quot;Draw 46: 0.666666666666657&amp;quot;
## [1] &amp;quot;Draw 47: 0.666666666666662&amp;quot;
## [1] &amp;quot;Draw 48: 0.666666666666664&amp;quot;
## [1] &amp;quot;Draw 49: 0.666666666666666&amp;quot;
## [1] &amp;quot;Draw 50: 0.666666666666666&amp;quot;
## [1] &amp;quot;Draw 51: 0.666666666666666&amp;quot;
## [1] &amp;quot;Draw 52: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 53: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 54: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 55: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 56: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 57: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 58: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 59: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 60: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 61: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 62: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 63: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 64: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 65: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 66: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 67: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 68: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 69: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 70: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 71: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 72: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 73: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 74: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 75: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 76: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 77: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 78: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 79: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 80: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 81: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 82: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 83: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 84: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 85: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 86: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 87: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 88: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 89: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 90: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 91: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 92: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 93: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 94: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 95: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 96: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 97: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 98: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 99: 0.666666666666667&amp;quot;
## [1] &amp;quot;Draw 100: 0.666666666666667&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The probabilities found up to draw 1, 3 and 5 are coherent with what we found in the previous sections. Moreover, we see that from draw 52 onwards, the probability of Louana winning remains constant at 66.67%. This is referred as the limit.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;game-limited-to-the-number-of-necessary-draws&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Game limited to the number of necessary draws&lt;/h2&gt;
&lt;p&gt;Without printing the results of the above &lt;code&gt;for loop&lt;/code&gt;, we do not know how many draws are necessary to reach the limit.&lt;/p&gt;
&lt;p&gt;Let’s now try to include the information about the number of necessary draws in order to avoid computing unnecessary draws:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;n_draws &amp;lt;- 9999 # initial number of draws, set intentionally to a high number
p_tie &amp;lt;- c() # set empty vector for prob of ties
l_win_tot &amp;lt;- c() # set empty vector for prob of Louana winning

# find number of necessary draws:
for (i in 1:n_draws) {
  p_tie[i] &amp;lt;- tie^i # prob of tie for each draw
  limit_ndraws &amp;lt;- sum(p_tie &amp;gt; 2.2e-16) # number of necessary draws
}

# compute Louana winning probabilities with the smallest number of necessary draws
for (i in 1:limit_ndraws) {
  l_win_tot[i] &amp;lt;- ((tie^(i - 1)) * l_win) # prob of Louana winning up to limited number of draws
  print(paste0(&amp;quot;Draw &amp;quot;, i, &amp;quot;: &amp;quot;, sum(l_win_tot))) # sum of winning up to limited number of draws
}&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;Draw 1: 0.333333333333333&amp;quot;
## [1] &amp;quot;Draw 2: 0.5&amp;quot;
## [1] &amp;quot;Draw 3: 0.583333333333333&amp;quot;
## [1] &amp;quot;Draw 4: 0.625&amp;quot;
## [1] &amp;quot;Draw 5: 0.645833333333333&amp;quot;
## [1] &amp;quot;Draw 6: 0.65625&amp;quot;
## [1] &amp;quot;Draw 7: 0.661458333333333&amp;quot;
## [1] &amp;quot;Draw 8: 0.6640625&amp;quot;
## [1] &amp;quot;Draw 9: 0.665364583333333&amp;quot;
## [1] &amp;quot;Draw 10: 0.666015625&amp;quot;
## [1] &amp;quot;Draw 11: 0.666341145833333&amp;quot;
## [1] &amp;quot;Draw 12: 0.66650390625&amp;quot;
## [1] &amp;quot;Draw 13: 0.666585286458333&amp;quot;
## [1] &amp;quot;Draw 14: 0.6666259765625&amp;quot;
## [1] &amp;quot;Draw 15: 0.666646321614583&amp;quot;
## [1] &amp;quot;Draw 16: 0.666656494140625&amp;quot;
## [1] &amp;quot;Draw 17: 0.666661580403646&amp;quot;
## [1] &amp;quot;Draw 18: 0.666664123535156&amp;quot;
## [1] &amp;quot;Draw 19: 0.666665395100911&amp;quot;
## [1] &amp;quot;Draw 20: 0.666666030883789&amp;quot;
## [1] &amp;quot;Draw 21: 0.666666348775228&amp;quot;
## [1] &amp;quot;Draw 22: 0.666666507720947&amp;quot;
## [1] &amp;quot;Draw 23: 0.666666587193807&amp;quot;
## [1] &amp;quot;Draw 24: 0.666666626930237&amp;quot;
## [1] &amp;quot;Draw 25: 0.666666646798452&amp;quot;
## [1] &amp;quot;Draw 26: 0.666666656732559&amp;quot;
## [1] &amp;quot;Draw 27: 0.666666661699613&amp;quot;
## [1] &amp;quot;Draw 28: 0.66666666418314&amp;quot;
## [1] &amp;quot;Draw 29: 0.666666665424903&amp;quot;
## [1] &amp;quot;Draw 30: 0.666666666045785&amp;quot;
## [1] &amp;quot;Draw 31: 0.666666666356226&amp;quot;
## [1] &amp;quot;Draw 32: 0.666666666511446&amp;quot;
## [1] &amp;quot;Draw 33: 0.666666666589056&amp;quot;
## [1] &amp;quot;Draw 34: 0.666666666627862&amp;quot;
## [1] &amp;quot;Draw 35: 0.666666666647264&amp;quot;
## [1] &amp;quot;Draw 36: 0.666666666656965&amp;quot;
## [1] &amp;quot;Draw 37: 0.666666666661816&amp;quot;
## [1] &amp;quot;Draw 38: 0.666666666664241&amp;quot;
## [1] &amp;quot;Draw 39: 0.666666666665454&amp;quot;
## [1] &amp;quot;Draw 40: 0.66666666666606&amp;quot;
## [1] &amp;quot;Draw 41: 0.666666666666364&amp;quot;
## [1] &amp;quot;Draw 42: 0.666666666666515&amp;quot;
## [1] &amp;quot;Draw 43: 0.666666666666591&amp;quot;
## [1] &amp;quot;Draw 44: 0.666666666666629&amp;quot;
## [1] &amp;quot;Draw 45: 0.666666666666648&amp;quot;
## [1] &amp;quot;Draw 46: 0.666666666666657&amp;quot;
## [1] &amp;quot;Draw 47: 0.666666666666662&amp;quot;
## [1] &amp;quot;Draw 48: 0.666666666666664&amp;quot;
## [1] &amp;quot;Draw 49: 0.666666666666666&amp;quot;
## [1] &amp;quot;Draw 50: 0.666666666666666&amp;quot;
## [1] &amp;quot;Draw 51: 0.666666666666666&amp;quot;
## [1] &amp;quot;Draw 52: 0.666666666666667&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;final-winning-probabilities&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Final winning probabilities&lt;/h2&gt;
&lt;p&gt;Remember that the initial question was:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;What is the probability of winning the game for each ambassador?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The probability that Louana wins the game can easily be extracted as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sum(l_win_tot)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.6666667&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And since the game only stops when there is a winner, the sum of the winning probabilities for Louana and Colin must be equal to 1, so the probability that Colin wins the game is:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;c_win_tot &amp;lt;- 1 - sum(l_win_tot)
c_win_tot&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.3333333&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;To summarize:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Louana has 66.67% chance to win the ambassadors’ game.&lt;/li&gt;
&lt;li&gt;Colin has 33.33% chance to win the ambassadors’ game.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;visual-representations&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Visual representations&lt;/h2&gt;
&lt;p&gt;To visualize the probabilities for each ambassador, we miss the probabilities of winning for Colin so let’s compute them first:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;c_win_tot &amp;lt;- c() # set empty vector for prob of Colin winning

# compute Colin winning probabilities with the smallest number of necessary draws
for (i in 1:limit_ndraws) {
  c_win_tot[i] &amp;lt;- ((tie^(i - 1)) * c_win) # prob of Colin winning
  print(paste0(&amp;quot;Draw &amp;quot;, i, &amp;quot;: &amp;quot;, sum(c_win_tot))) # print sum of winning
}&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;Draw 1: 0.166666666666667&amp;quot;
## [1] &amp;quot;Draw 2: 0.25&amp;quot;
## [1] &amp;quot;Draw 3: 0.291666666666667&amp;quot;
## [1] &amp;quot;Draw 4: 0.3125&amp;quot;
## [1] &amp;quot;Draw 5: 0.322916666666667&amp;quot;
## [1] &amp;quot;Draw 6: 0.328125&amp;quot;
## [1] &amp;quot;Draw 7: 0.330729166666667&amp;quot;
## [1] &amp;quot;Draw 8: 0.33203125&amp;quot;
## [1] &amp;quot;Draw 9: 0.332682291666667&amp;quot;
## [1] &amp;quot;Draw 10: 0.3330078125&amp;quot;
## [1] &amp;quot;Draw 11: 0.333170572916667&amp;quot;
## [1] &amp;quot;Draw 12: 0.333251953125&amp;quot;
## [1] &amp;quot;Draw 13: 0.333292643229167&amp;quot;
## [1] &amp;quot;Draw 14: 0.33331298828125&amp;quot;
## [1] &amp;quot;Draw 15: 0.333323160807292&amp;quot;
## [1] &amp;quot;Draw 16: 0.333328247070312&amp;quot;
## [1] &amp;quot;Draw 17: 0.333330790201823&amp;quot;
## [1] &amp;quot;Draw 18: 0.333332061767578&amp;quot;
## [1] &amp;quot;Draw 19: 0.333332697550456&amp;quot;
## [1] &amp;quot;Draw 20: 0.333333015441895&amp;quot;
## [1] &amp;quot;Draw 21: 0.333333174387614&amp;quot;
## [1] &amp;quot;Draw 22: 0.333333253860474&amp;quot;
## [1] &amp;quot;Draw 23: 0.333333293596904&amp;quot;
## [1] &amp;quot;Draw 24: 0.333333313465118&amp;quot;
## [1] &amp;quot;Draw 25: 0.333333323399226&amp;quot;
## [1] &amp;quot;Draw 26: 0.33333332836628&amp;quot;
## [1] &amp;quot;Draw 27: 0.333333330849806&amp;quot;
## [1] &amp;quot;Draw 28: 0.33333333209157&amp;quot;
## [1] &amp;quot;Draw 29: 0.333333332712452&amp;quot;
## [1] &amp;quot;Draw 30: 0.333333333022892&amp;quot;
## [1] &amp;quot;Draw 31: 0.333333333178113&amp;quot;
## [1] &amp;quot;Draw 32: 0.333333333255723&amp;quot;
## [1] &amp;quot;Draw 33: 0.333333333294528&amp;quot;
## [1] &amp;quot;Draw 34: 0.333333333313931&amp;quot;
## [1] &amp;quot;Draw 35: 0.333333333323632&amp;quot;
## [1] &amp;quot;Draw 36: 0.333333333328483&amp;quot;
## [1] &amp;quot;Draw 37: 0.333333333330908&amp;quot;
## [1] &amp;quot;Draw 38: 0.333333333332121&amp;quot;
## [1] &amp;quot;Draw 39: 0.333333333332727&amp;quot;
## [1] &amp;quot;Draw 40: 0.33333333333303&amp;quot;
## [1] &amp;quot;Draw 41: 0.333333333333182&amp;quot;
## [1] &amp;quot;Draw 42: 0.333333333333258&amp;quot;
## [1] &amp;quot;Draw 43: 0.333333333333295&amp;quot;
## [1] &amp;quot;Draw 44: 0.333333333333314&amp;quot;
## [1] &amp;quot;Draw 45: 0.333333333333324&amp;quot;
## [1] &amp;quot;Draw 46: 0.333333333333329&amp;quot;
## [1] &amp;quot;Draw 47: 0.333333333333331&amp;quot;
## [1] &amp;quot;Draw 48: 0.333333333333332&amp;quot;
## [1] &amp;quot;Draw 49: 0.333333333333333&amp;quot;
## [1] &amp;quot;Draw 50: 0.333333333333333&amp;quot;
## [1] &amp;quot;Draw 51: 0.333333333333333&amp;quot;
## [1] &amp;quot;Draw 52: 0.333333333333333&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We create a dataset with the probabilities for both ambassadors:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- data.frame(
  Draw = rep(1:limit_ndraws, 2),
  Probability = c(cumsum(l_win_tot), cumsum(c_win_tot)),
  Ambassador = c(rep(&amp;quot;Louana&amp;quot;, limit_ndraws), rep(&amp;quot;Colin&amp;quot;, limit_ndraws))
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can now visualize these probabilities up to the number of necessary draws:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load package
library(ggplot2)

# plot
ggplot(dat) +
  aes(x = Draw, y = Probability, colour = Ambassador) +
  geom_line(linewidth = 2L) +
  labs(
    y = &amp;quot;Probability of winning&amp;quot;,
    caption = &amp;quot;Source: Koh-Lanta 2022&amp;quot;
  ) +
  scale_y_continuous(labels = scales::percent_format(accuracy = 1), limits = c(0, 1)) +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/koh-lanta-2022-ambassadors-probability-problem/index_files/figure-html/unnamed-chunk-14-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;But I believe the most appropriate plot to answer the initial question is with a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#barplot&#34;&gt;barplot&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# create dataset
dat_barplot &amp;lt;- data.frame(
  Ambassador = c(&amp;quot;Louana&amp;quot;, &amp;quot;Colin&amp;quot;),
  Probability = c(sum(l_win_tot), sum(c_win_tot))
)

# plot
ggplot(data = dat_barplot, aes(x = Ambassador, y = Probability)) +
  geom_bar(stat = &amp;quot;identity&amp;quot;, fill = &amp;quot;steelblue&amp;quot;) +
  labs(
    y = &amp;quot;Probability of winning&amp;quot;,
    caption = &amp;quot;Source: Koh-Lanta 2022&amp;quot;
  ) +
  scale_y_continuous(labels = scales::percent_format(accuracy = 1), limits = c(0, 1)) +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/koh-lanta-2022-ambassadors-probability-problem/index_files/figure-html/unnamed-chunk-15-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;coded-into-a-function&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Coded into a function&lt;/h2&gt;
&lt;p&gt;Let’s try to implement this problem in a function to be able to reuse it with other initial probabilities.&lt;/p&gt;
&lt;p&gt;With:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;p_a&lt;/code&gt; and &lt;code&gt;p_b&lt;/code&gt; denoting, respectively, the probability that ambassador A and ambassador B draw a white ball,&lt;/li&gt;
&lt;li&gt;&lt;code&gt;n_draws&lt;/code&gt; denoting the maximum number of draws that is allowed (default = 9999),&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;we have the following function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ambassadors_game &amp;lt;- function(p_a, p_b, n_draws = 9999) {
  q_a &amp;lt;- (1 - p_a)
  q_b &amp;lt;- (1 - p_b)

  a_win &amp;lt;- q_b * p_a
  b_win &amp;lt;- q_a * p_b

  tie &amp;lt;- (p_a * p_b) + (q_a * q_b)

  p_tie &amp;lt;- c() # set empty vector for prob of ties
  a_win_tot &amp;lt;- c() # set empty vector for prob of A winning
  b_win_tot &amp;lt;- c() # set empty vector for prob of B winning

  # find number of necessary draws:
  for (i in 1:n_draws) {
    p_tie[i] &amp;lt;- tie^i # prob of tie for each draw
    limit_ndraws &amp;lt;- sum(p_tie &amp;gt; 2.2e-16) # number of necessary draws
  }

  # compute A and B winning probabilities with the smallest number of necessary draws:
  for (i in 1:limit_ndraws) {
    a_win_tot[i] &amp;lt;- ((tie^(i - 1)) * a_win) # prob of A winning up to limited number of draws
    b_win_tot[i] &amp;lt;- ((tie^(i - 1)) * b_win) # prob of B winning up to limited number of draws
  }

  # save P(A), P(B) and number of necessary draws:
  res &amp;lt;- list(
    &amp;quot;p_a&amp;quot; = sum(a_win_tot),
    &amp;quot;p_b&amp;quot; = sum(b_win_tot),
    &amp;quot;ndraws&amp;quot; = limit_ndraws
  )
  # print results:
  return(res)
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We test the function to see if it matches results found above.&lt;/p&gt;
&lt;p&gt;First, if both ambassadors have identical urns as it was the case before the 2022 season:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ambassadors_game(
  p_a = 1 / 2,
  p_b = 1 / 2
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $p_a
## [1] 0.5
## 
## $p_b
## [1] 0.5
## 
## $ndraws
## [1] 52&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The game is indeed fair, with a 50% chance of winning for each ambassador.&lt;/p&gt;
&lt;p&gt;Second, with the urns presented to Louana and Colin, but for the first draw only (setting arbitrarily that Louana is ambassador A and Colin is ambassador B):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# first draw only
ambassadors_game(
  p_a = 1 / 2,
  p_b = 1 / 3,
  n_draws = 1
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $p_a
## [1] 0.3333333
## 
## $p_b
## [1] 0.1666667
## 
## $ndraws
## [1] 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Third, still with the urns presented to Louana and Colin, but for a game limited to exactly 3 and 5 draws:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# up to 3 draws
ambassadors_game(
  p_a = 1 / 2,
  p_b = 1 / 3,
  n_draws = 3
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $p_a
## [1] 0.5833333
## 
## $p_b
## [1] 0.2916667
## 
## $ndraws
## [1] 3&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# up to 5 draws
ambassadors_game(
  p_a = 1 / 2,
  p_b = 1 / 3,
  n_draws = 5
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $p_a
## [1] 0.6458333
## 
## $p_b
## [1] 0.3229167
## 
## $ndraws
## [1] 5&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And now, the final verification with the real situation of Louana and Colin in Koh-Lanta 2022:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Koh-Lanta 2022 situation
out &amp;lt;- ambassadors_game(
  p_a = 1 / 2,
  p_b = 1 / 3
)

out&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $p_a
## [1] 0.6666667
## 
## $p_b
## [1] 0.3333333
## 
## $ndraws
## [1] 52&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;All results match the ones presented above.&lt;/p&gt;
&lt;p&gt;(Note that the probabilities for each ambassador can be extracted as follows:)&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# prob ambassador A
out$p_a&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.6666667&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# prob ambassador B
out$p_b&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.3333333&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;The initial question, coming from the television show Koh-Lanta, was “what is the probability of winning for each participant if they play the ambassadors’ game?”.&lt;/p&gt;
&lt;p&gt;In this article, we have shown how to compute these probabilities. Moreover, we have illustrated the process of how a simple probability problem could be generalized to suit many real life situations, and how a &lt;code&gt;for loop&lt;/code&gt; and a function could be used to implement a real life situation into R.&lt;/p&gt;
&lt;p&gt;Last but not least, I would like to focus on something Denis Brogniart (the well-known presenter of the show) said just after the two ambassadors came back to the island to announce their choice to the other adventurers. He mentioned that, due to the punishment afflicted to the yellow tribe, there was a difference of chances of 16% between Louana and Colin.&lt;/p&gt;
&lt;p&gt;This comes naturally from the following two situations:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;First situation:&lt;/em&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Louana has a 50% chance of picking a white ball.&lt;/li&gt;
&lt;li&gt;Colin has a 33.33% chance of picking a white ball.&lt;/li&gt;
&lt;li&gt;The difference is 50 - 33.33 = 16.67%, truncated to 16%.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Or, if the game is limited to the first draw only:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Second situation:&lt;/em&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Louana has 33.33% chance of winning the game.&lt;/li&gt;
&lt;li&gt;Colin has a 16.67% chance of winning the game.&lt;/li&gt;
&lt;li&gt;The difference is 33.33 - 16.67 = 16.66%, truncated to 16%.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;It is true that, seeing the problem from those two angles, the difference is ~16%. Denis Brogniart is right in mentioning this 16% difference.&lt;/p&gt;
&lt;p&gt;However, the difference of chances between the two ambassadors is larger &lt;em&gt;if we see the game from a broader perspective&lt;/em&gt;. The rules of the game say that it stops only when there is a winner. From that point of view, as demonstrated above:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Louana has 66.67% chance of winning the game.&lt;/li&gt;
&lt;li&gt;Colin has 33.33% chance of winning the game.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In this situation, the difference in probability of winning between the 2 ambassadors is 66.67 - 33.33 = 33.34%!&lt;/p&gt;
&lt;p&gt;I must admit that I was not expecting such a large difference between the two ambassadors. Seeing the ambassadors’ game from that perspective looks different to what we were told, or to what we thought before actually computing the probabilities. (Denis Brogniart, if you happen to read this, feel free to let me know whether this relatively large difference was intended or not.)&lt;/p&gt;
&lt;p&gt;For those of you who do not watch the show: upon the return of the ambassadors on the island with all adventurers, Colin has been heavily criticized by the members of his tribe. His decision not to play the ambassadors’ game (and the decision to eliminate one member of his tribe with the aim of saving himself) was seen as a betrayal. As a consequence of this, he was eliminated by the reunited tribe directly after that episode.&lt;/p&gt;
&lt;p&gt;I am going to conclude this article with the following question:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;If you were an ambassador in the 2022 Koh-Lanta season and given that now you know the exact probabilites of winning for each tribe, what would you have done?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;As always, if you have any question related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;We will never know if he would have played the game if the chances of winning were equal for both ambassadors. Since I started to watch this television show, I have never seen any ambassadors’ negotiation leading to the ambassadors’ game, they all ended with the designation of an adventurer.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;And to be honest, I wanted to compute these probabilities because while I was watching the show with my girlfriend, she looked at me and asked “what are the probabilities for each of them?”. I am now able to give her a precise answer.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Paper: &#39;Semi-Markov modeling for cancer insurance&#39;</title>
      <link>https://statsandr.com/blog/paper-semi-markov-modeling-for-cancer-insurance/</link>
      <pubDate>Wed, 06 Apr 2022 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/paper-semi-markov-modeling-for-cancer-insurance/</guid>
      <description>


&lt;p&gt;&lt;img src=&#34;images/Semi-Markov%20modeling%20for%20cancer%20insurance.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;I am happy to announce that our paper entitled “&lt;a href=&#34;https://rdcu.be/cKLGO&#34;&gt;Semi-Markov modeling for cancer insurance&lt;/a&gt;” has been accepted for publication in the European Actuarial Journal &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-soetewey2022semi&#34; role=&#34;doc-biblioref&#34;&gt;Soetewey et al. 2022&lt;/a&gt;)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Advancements in medicine and biostatistics have already resulted in a better access to insurance for people diagnosed with cancer. This materializes into the “right to be forgotten” adopted in several EU member states, granting access to insurance after a waiting period of at most 10 years starting at the end of the successful therapeutic protocol.&lt;/p&gt;
&lt;p&gt;This paper concentrates on insurance covers on a market where such a right has been implemented. Stand-alone products are considered, as well as guarantees included as a rider in an existing package. The cost of offering standard premium rates to all applicants in mortgage insurance related to property loans is also evaluated.&lt;/p&gt;
&lt;p&gt;The 3-state (healthy—ill—dead) Semi-Markov hierarchical model developed in Denuit et al. (2019) for long-term care insurance is adopted here for actuarial calculations. Semi-Markov transition intensities are estimated from cancer cases recorded by the Belgian Cancer Registry. The obtained results suggest that a new offer could develop, targeting the particular needs of cancer patients.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Read more &lt;a href=&#34;https://rdcu.be/cKLGO&#34;&gt;here&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Note that this paper is written jointly with Prof. Legrand and Prof. Denuit—my PhD supervisors at UCLouvain—and Dr. Silversmit from the Belgian Cancer Registry.&lt;/p&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this paper will, to some extent, be helpful for your research.&lt;/p&gt;
&lt;p&gt;As always, if you have any question related to the topic covered in this paper, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;div id=&#34;references&#34; class=&#34;section level2 unnumbered&#34;&gt;
&lt;h2&gt;References&lt;/h2&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-soetewey2022semi&#34; class=&#34;csl-entry&#34;&gt;
Soetewey, Antoine, Catherine Legrand, Michel Denuit, and Geert Silversmit. 2022. &lt;span&gt;“Semi-Markov Modeling for Cancer Insurance.”&lt;/span&gt; &lt;em&gt;European Actuarial Journal&lt;/em&gt;, 1–25. &lt;a href=&#34;https://doi.org/10.1007/s13385-022-00308-2&#34;&gt;https://doi.org/10.1007/s13385-022-00308-2&lt;/a&gt;.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Kruskal-Wallis test, or the nonparametric version of the ANOVA</title>
      <link>https://statsandr.com/blog/kruskal-wallis-test-nonparametric-version-anova/</link>
      <pubDate>Thu, 24 Mar 2022 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/kruskal-wallis-test-nonparametric-version-anova/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#data&#34; id=&#34;toc-data&#34;&gt;Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#kruskal-wallis-test&#34; id=&#34;toc-kruskal-wallis-test&#34;&gt;Kruskal-Wallis test&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#aim-and-hypotheses&#34; id=&#34;toc-aim-and-hypotheses&#34;&gt;Aim and hypotheses&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#assumptions&#34; id=&#34;toc-assumptions&#34;&gt;Assumptions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#in-r&#34; id=&#34;toc-in-r&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#interpretations&#34; id=&#34;toc-interpretations&#34;&gt;Interpretations&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#post-hoc-tests&#34; id=&#34;toc-post-hoc-tests&#34;&gt;Post-hoc tests&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#dunn-test&#34; id=&#34;toc-dunn-test&#34;&gt;Dunn test&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#combination-of-statistical-results-and-plot&#34; id=&#34;toc-combination-of-statistical-results-and-plot&#34;&gt;Combination of statistical results and plot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#summary&#34; id=&#34;toc-summary&#34;&gt;Summary&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;images/kruskal-wallis-test-nonparametric-version-anova.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;In a previous article, we showed how to do an &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;ANOVA in R&lt;/a&gt; to compare three or more groups.&lt;/p&gt;
&lt;p&gt;Remember that, as for many &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt;, the one-way ANOVA requires that some assumptions are satisfied in order to be able to use and interpret the results. In particular, the ANOVA requires that residuals follow approximately a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution&lt;/a&gt;.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Luckily, if the normality assumption is not satisfied, there is the nonparametric version of the ANOVA: the &lt;strong&gt;Kruskal-Wallis&lt;/strong&gt; test.&lt;/p&gt;
&lt;p&gt;In the rest of the article, we show how to perform the Kruskal-Wallis test in R and how to interpret its results. We will also briefly show how to do post-hoc tests and how to present all necessary statistical results directly on a plot.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;data&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Data&lt;/h1&gt;
&lt;p&gt;Data for the present article is based on the &lt;code&gt;penguins&lt;/code&gt; dataset (an alternative to the well-known &lt;code&gt;iris&lt;/code&gt; dataset), accessible via the &lt;code&gt;{palmerpenguins}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# install.packages(&amp;quot;palmerpenguins&amp;quot;)
library(palmerpenguins)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The original dataset contains data for 344 penguins of 3 different species (Adelie, Chinstrap and Gentoo).&lt;/p&gt;
&lt;p&gt;It contains 8 variables, but we focus only on the flipper length and the species for this article, so we keep only those 2 variables:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(tidyverse)

dat &amp;lt;- penguins %&amp;gt;%
  select(species, flipper_length_mm)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;(If you are unfamiliar with the pipe operator (&lt;code&gt;%&amp;gt;%&lt;/code&gt;), you can also select variables with &lt;code&gt;penguins[, c(&#34;species&#34;, &#34;flipper_length_mm&#34;)]&lt;/code&gt;. Learn more ways to select variables in the article about &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/&#34;&gt;data manipulation&lt;/a&gt;.)&lt;/p&gt;
&lt;p&gt;It is always a good practice to do some &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt; for the entire sample and by group before doing the test, so we have a broad overview of the data at hand.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# entire sample
summary(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       species    flipper_length_mm
##  Adelie   :152   Min.   :172.0    
##  Chinstrap: 68   1st Qu.:190.0    
##  Gentoo   :124   Median :197.0    
##                  Mean   :200.9    
##                  3rd Qu.:213.0    
##                  Max.   :231.0    
##                  NA&amp;#39;s   :2&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# by group
library(doBy)
summaryBy(flipper_length_mm ~ species,
  data = dat,
  FUN = median,
  na.rm = TRUE
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 2
##   species   flipper_length_mm.median
##   &amp;lt;fct&amp;gt;                        &amp;lt;dbl&amp;gt;
## 1 Adelie                         190
## 2 Chinstrap                      196
## 3 Gentoo                         216&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# boxplot by species
ggplot(dat) +
  aes(x = species, y = flipper_length_mm, fill = species) +
  geom_boxplot() +
  theme(legend.position = &amp;quot;none&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/kruskal-wallis-test-nonparametric-version-anova/index_files/figure-html/unnamed-chunk-3-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Based on the boxplots and the summary statistics, we already see that, in our &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;sample&lt;/a&gt;, penguins from the Adelie species seem to have the smallest flippers, while those from the Gentoo species seem to have the biggest flippers. However, only a sound statistical test will tell us whether we can infer this conclusion to our &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;population&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;kruskal-wallis-test&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Kruskal-Wallis test&lt;/h1&gt;
&lt;div id=&#34;aim-and-hypotheses&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Aim and hypotheses&lt;/h2&gt;
&lt;p&gt;As mentioned earlier, the Kruskal-Wallis test allows to compare three or more groups. More precisely, it is used to compare three or more groups in terms of a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#quantitative&#34;&gt;quantitative variable&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;It can be seen as the extension to the &lt;a href=&#34;https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/&#34;&gt;Mann-Whitney&lt;/a&gt; test which allows to compare 2 groups under the non-normality assumption.&lt;/p&gt;
&lt;p&gt;In the context of our example, we are going to use the Kruskal-Wallis test to help us answer the following question: “Is the length of the flippers different between the 3 species of penguins?”.&lt;/p&gt;
&lt;p&gt;The null and alternative hypotheses of the Kruskal-Wallis test are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: The 3 species are equal in terms of flipper length&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: At least one species is different from the other 2 species in terms of flipper length&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Be careful that, as for the ANOVA, the alternative hypothesis is &lt;strong&gt;&lt;em&gt;not&lt;/em&gt;&lt;/strong&gt; that all species are different in terms of flipper length. The opposite of all species being equal (&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;) is that &lt;em&gt;at least&lt;/em&gt; one species is different from the others (&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;).&lt;/p&gt;
&lt;p&gt;In this sense, if the null hypothesis is rejected, it means that at least one species is different from the other 2, but not necessarily that all 3 species are different from each other. It could be that flipper length for the species Gentoo is different than for the species Chinstrap and Adelie, but flipper length is similar between Chinstrap and Adelie. Other types of test (known as post-hoc tests and covered later) must be performed to test whether all 3 species differ.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;assumptions&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Assumptions&lt;/h2&gt;
&lt;p&gt;First, the Kruskal-Wallis test compares several groups in terms of a quantitative variable. So there must be one quantitative dependent variable (which corresponds to the measurements to which the question relates) and one qualitative independent variable (with at least 2 levels which will determine the groups to compare).&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Second, remember that the Kruskal-Wallis test is a nonparametric test, so the &lt;strong&gt;normality assumption is not required&lt;/strong&gt;. However, the &lt;strong&gt;independence assumption still holds&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;This means that the data, collected from a representative and randomly selected portion of the total population, should be independent between groups and within each group. The assumption of independence is most often verified based on the design of the experiment and on the good control of experimental conditions rather than via a formal test. If you are still unsure about independence based on the experiment design, ask yourself if one observation is related to another (if one observation has an impact on another) within each group or between the groups themselves. If not, it is most likely that you have independent samples. If observations between samples (forming the different groups to be compared) are dependent (for example, if three measurements have been collected on the &lt;strong&gt;same individuals&lt;/strong&gt; as it is often the case in medical studies when measuring a metric (i) before, (ii) during and (iii) after a treatment), the Friedman test should be preferred in order to take into account the dependency between the samples.&lt;/p&gt;
&lt;p&gt;Regarding the homoscedasticity (i.e., equality of the variances): As long as you use the Kruskal-Wallis test to, &lt;em&gt;in fine&lt;/em&gt;, compare groups, homoscedasticity is not required. If you wish to compare medians, the Kruskal-Wallis test requires homoscedasticity.&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In our example, independence is assumed and we do not need to compare medians (we are only interested in comparing groups), so we can proceed to how to do the test in R. Note that the normality assumption may or may not hold, but for this article we assume it is &lt;em&gt;not&lt;/em&gt; satisfied.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;In R&lt;/h2&gt;
&lt;p&gt;The Kruskal-Wallis test in R can be done with the &lt;code&gt;kruskal.test()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;kruskal.test(flipper_length_mm ~ species,
  data = dat
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Kruskal-Wallis rank sum test
## 
## data:  flipper_length_mm by species
## Kruskal-Wallis chi-squared = 244.89, df = 2, p-value &amp;lt; 2.2e-16&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The most important result in this output is the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/#a-note-on-p-value-and-significance-level-alpha&#34;&gt;&lt;em&gt;p&lt;/em&gt;-value&lt;/a&gt;. We show how to interpret it in the next section.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;interpretations&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Interpretations&lt;/h2&gt;
&lt;p&gt;Based on the Kruskal-Wallis test, we reject the null hypothesis and we conclude that at least one species is different in terms of flippers length (&lt;em&gt;p&lt;/em&gt;-value &amp;lt; 0.001).&lt;/p&gt;
&lt;p&gt;(&lt;em&gt;For the sake of illustration&lt;/em&gt;, if the &lt;em&gt;p&lt;/em&gt;-value was larger than the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;: we cannot reject the null hypothesis so we cannot reject the hypothesis that the 3 considered species of penguins are equal in terms of flippers length.)&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;post-hoc-tests&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Post-hoc tests&lt;/h1&gt;
&lt;p&gt;We have just showed that at least one species is different from the others in terms of flippers length. Nonetheless, here comes the limitations of the Kruskal-Wallis test: it does not say which group(s) is(are) different from the others.&lt;/p&gt;
&lt;p&gt;To know this, we need to use other types of test, referred as post-hoc tests (in Latin, “after this”, so after obtaining statistically significant Kruskal-Wallis results) or multiple pairwise-comparison tests. For the interested reader, a more detailed explanation of post-hoc tests can be found &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#post-hoc-test&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The most common post-hoc tests after a significant Kruskal-Wallis test are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Dunn test&lt;/li&gt;
&lt;li&gt;Conover test&lt;/li&gt;
&lt;li&gt;Nemenyi test&lt;/li&gt;
&lt;li&gt;Pairwise Wilcoxon test&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The Dunn test being the most common one, here is how to do it in R.&lt;a href=&#34;#fn4&#34; class=&#34;footnote-ref&#34; id=&#34;fnref4&#34;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;div id=&#34;dunn-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Dunn test&lt;/h2&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(FSA)

dunnTest(flipper_length_mm ~ species,
  data = dat,
  method = &amp;quot;holm&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##           Comparison          Z      P.unadj        P.adj
## 1 Adelie - Chinstrap  -3.629336 2.841509e-04 2.841509e-04
## 2    Adelie - Gentoo -15.476612 4.990733e-54 1.497220e-53
## 3 Chinstrap - Gentoo  -8.931938 4.186100e-19 8.372200e-19&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is the last column (the adjusted &lt;em&gt;p&lt;/em&gt;-values, adjusted for multiple comparisons) that is of interest. These &lt;em&gt;p&lt;/em&gt;-values should be compared to your desired &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/#a-note-on-p-value-and-significance-level-alpha&#34;&gt;significance level&lt;/a&gt; (usually 5%).&lt;/p&gt;
&lt;p&gt;Based on the output, we conclude that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Adelie and Chinstrap differ significantly (p &amp;lt; 0.001)&lt;/li&gt;
&lt;li&gt;Adelie and Gentoo differ significantly (p &amp;lt; 0.001)&lt;/li&gt;
&lt;li&gt;Chinstrap and Gentoo differ significantly (p &amp;lt; 0.001)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Therefore, based on the Dunn test, we can now conclude that &lt;strong&gt;all 3 species differ in terms of flipper length&lt;/strong&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;combination-of-statistical-results-and-plot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Combination of statistical results and plot&lt;/h1&gt;
&lt;p&gt;A very good alternative for performing a Kruskal-Wallis and the post-hoc tests in R is with the &lt;code&gt;ggbetweenstats()&lt;/code&gt; function from the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggstatsplot)

ggbetweenstats(
  data = dat,
  x = species,
  y = flipper_length_mm,
  type = &amp;quot;nonparametric&amp;quot;, # ANOVA or Kruskal-Wallis
  plot.type = &amp;quot;box&amp;quot;,
  pairwise.comparisons = TRUE,
  pairwise.display = &amp;quot;significant&amp;quot;,
  centrality.plotting = FALSE,
  bf.message = FALSE
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/kruskal-wallis-test-nonparametric-version-anova/index_files/figure-html/unnamed-chunk-6-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;This method has the advantage that all necessary statistical results are displayed directly on the plot.&lt;/p&gt;
&lt;p&gt;The results of the Kruskal-Wallis test are shown in the subtitle above the plot (the &lt;em&gt;p&lt;/em&gt;-value is after &lt;code&gt;p =&lt;/code&gt;). Moreover, the results of the post-hoc test are displayed between each group via accolades, and the boxplots allow to visualize the distribution for each species.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;summary&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;In this post, we reviewed the aim and hypotheses of the Kruskal-Wallis test and its underlying assumptions. We then showed how to do the test in R and how to interpret the results.&lt;/p&gt;
&lt;p&gt;We also showed the most common post-hoc test after a significant Kruskal-Wallis test—the Dunn test.&lt;/p&gt;
&lt;p&gt;Last but not least, we presented a concise way to present both the data by group and all the statistical results on the same plot.&lt;/p&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-stevens2013intermediate&#34; class=&#34;csl-entry&#34;&gt;
Stevens, James P. 2013. &lt;em&gt;Intermediate Statistics: A Modern Approach&lt;/em&gt;. Routledge.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;This is the case for small sample sizes. For large sample sizes, normality is not required (this is a common misconception!). By the &lt;a href=&#34;https://en.wikipedia.org/wiki/Central_limit_theorem&#34; target=&#34;_blank&#34;&gt;central limit theorem&lt;/a&gt;, sample means of large samples are often well-approximated by a normal distribution even if the data are not normally distributed &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-stevens2013intermediate&#34;&gt;Stevens 2013&lt;/a&gt;)&lt;/span&gt;. See more details in this &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#fn3&#34;&gt;note&lt;/a&gt;.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Note that in theory, Kruskal-Wallis test can also be used for only two groups. However, in practice we use the &lt;a href=&#34;https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/&#34;&gt;Mann-Whitney test&lt;/a&gt; for two groups and Kruskal-Wallis for three or more groups.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;See more information about the difference in this &lt;a href=&#34;https://influentialpoints.com/Training/Kruskal-Wallis_ANOVA_use_and_misuse.htm&#34; target=&#34;_blank&#34;&gt;article&lt;/a&gt;.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;Note that there are other &lt;em&gt;p&lt;/em&gt;-value adjustment methods. See &lt;code&gt;?dunnTest&lt;/code&gt; for more options.&lt;a href=&#34;#fnref4&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>What statistical test should I do?</title>
      <link>https://statsandr.com/blog/what-statistical-test-should-i-do/</link>
      <pubDate>Thu, 02 Dec 2021 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/what-statistical-test-should-i-do/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#flowchart&#34; id=&#34;toc-flowchart&#34;&gt;Flowchart&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#notes&#34; id=&#34;toc-notes&#34;&gt;Notes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;Being a &lt;a href=&#34;https://antoinesoetewey.com/teaching/&#34;&gt;teaching assistant&lt;/a&gt; in statistics for students with diverse backgrounds, I have the chance to see what is globally not well understood by students.&lt;/p&gt;
&lt;p&gt;I have realized that it is usually not a problem for students to do a specific statistical test when they are told which one to use (as long as they have good resources and they have been attentive during classes, of course). However, it appears that the task is much more difficult for them when they need to &lt;strong&gt;choose what test to do&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;This article presents a flowchart to help students in selecting the most appropriate statistical test based on a couple of criteria.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;flowchart&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Flowchart&lt;/h1&gt;
&lt;p&gt;&lt;a href=&#34;https://statsandr.com/blog/files/overview-statistical-tests-statsandr.pdf&#34;&gt;&lt;img src=&#34;images/overview-statistical-tests-statsandr.svg&#34; style=&#34;width:100.0%&#34; alt=&#34;Overview of statistical tests&#34; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Due to the large number of tests, the image is quite wide so it may not render well on all screens. In that case, you can see it in full screen by clicking directly on the image or by clicking on the following link:&lt;/p&gt;
&lt;center&gt;
&lt;a href=&#34;https://statsandr.com/blog/files/overview-statistical-tests-statsandr.pdf&#34;&gt;&lt;strong&gt;Download in PDF&lt;/strong&gt;&lt;/a&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;notes&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Notes&lt;/h1&gt;
&lt;p&gt;As you can see in the flowchart, the selection of the most appropriate test is based on:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the number of variables of interest: one, two or more than two variables&lt;/li&gt;
&lt;li&gt;the &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/&#34;&gt;variable type&lt;/a&gt;: &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#quantitative&#34;&gt;quantitative&lt;/a&gt; or &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;qualitative&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;in case of a qualitative variable, the number of groups and whether they are independent or paired (i.e., dependent)&lt;/li&gt;
&lt;li&gt;whether you want the parametric or nonparametric version&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Summarizing so many tests in a single image is not an easy task. The goal of this flowchart is to provide students with a &lt;strong&gt;quick and easy way to select the most appropriate statistical test&lt;/strong&gt; among the most common ones (or to see what are the alternatives).&lt;/p&gt;
&lt;p&gt;Obviously, this flowchart is not exhaustive. There are many other tests but most of them have been omitted on purpose to keep it simple and readable. I decided to keep it simple so that the flowchart is not overwhelming, with the hope that it is still complete and precise enough for most students.&lt;/p&gt;
&lt;p&gt;For the sake of completeness, here are a few additional remarks about this flowchart:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Tests for more than 2 variables are applicable to the case of 2 variables as well. For simplicity, I however tend to suggest the simplest test when more than one is possible. For instance, with two quantitative variables, both a &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;correlation test&lt;/a&gt; and a &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;simple linear regression&lt;/a&gt; can be done. In introductory statistics classes, I will most likely teach the concept of correlation but not necessarily the concept of linear regression. For this reason, I will most likely recommend a correlation test over a linear regression, unless the students have a more advanced level.&lt;/li&gt;
&lt;li&gt;The &lt;a href=&#34;https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test&#34; target=&#34;_blank&#34;&gt;Kolmogorov-Smirnov test&lt;/a&gt;, used to compare a sample with a reference probability distribution or to compare two samples, has been omitted because it is generally not taught in introductory classes. Keep in mind, however, that this test is useful both in the uni and bivariate cases.&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#normality-test&#34;&gt;Normality tests&lt;/a&gt; (such as, among others, the Shapiro-Wilk or Kolmogorov-Smirnov test) have also been omitted as they are part of another family of tests (they are used to answer the question “Is my dataset well-modeled by a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution&lt;/a&gt;?”). Remember, nonetheless, that they are very useful to verify the normality assumption required in many &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt;. For example, the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test&lt;/a&gt; requires that the data follow approximately a normal distribution in case of small sample size. If this is not the case, the nonparametric version (i.e., the &lt;a href=&#34;https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/&#34;&gt;Wilcoxon test&lt;/a&gt;) should be preferred. The same goes for &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;ANOVA&lt;/a&gt; and many other statistical tests.&lt;/li&gt;
&lt;li&gt;The flowchart could be extended to include more advanced linear or non-linear models, but this is beyond its scope and goal. Remember that I created it to help non-experts to see more clearly and have a broad overview of the &lt;strong&gt;most common statistical tests&lt;/strong&gt;, not to confuse them even more.&lt;/li&gt;
&lt;li&gt;If you open the flowchart in &lt;a href=&#34;https://statsandr.com/blog/files/overview-statistical-tests-statsandr.pdf&#34;&gt;PDF&lt;/a&gt;, you will be able to click on most of the tests. Clicking on the name of the test will redirect you to the corresponding article, which explains the test in further details. If the test is not clickable, it means I have not written about it yet. I will update the flowchart if I publish an article about one of the missing test.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this guide will help you in determining the right statistical test. Feel free to share it with all students who might be interested.&lt;/p&gt;
&lt;p&gt;As always, if you have a question or a suggestion (for example, if I missed a test which you believe should be included), please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;For those interested to draw flowcharts like this one, note that I used &lt;a href=&#34;https://www.diagrams.net/&#34; target=&#34;_blank&#34;&gt;diagrams.net&lt;/a&gt;. At the time of writing this article, it is free and you can synchronize it with Google Drive, GitHub, etc.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;A parametric test means that it is based on a theoretical statistical distribution, which depends on some defined parameters. On the contrary, a nonparametric test does not rely on data belonging to any particular parametric family of probability distributions. Nonparametric tests have the same objective as their parametric counterparts. However, they have two advantages over parametric tests: (i) they do not require the assumption of normality of distributions and (ii) they can deal with outliers. The trade-off is that nonparametric tests are usually less powerful than their corresponding parametric version when the normality assumption holds. Therefore, all else being equal, with a nonparametric test you are less likely to reject the &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#step-1-stating-the-null-and-alternative-hypothesis&#34;&gt;null hypothesis&lt;/a&gt; when it is false if the data follow a normal distribution. It is thus preferred to use the parametric version when the assumptions are met.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Multiple linear regression made simple</title>
      <link>https://statsandr.com/blog/multiple-linear-regression-made-simple/</link>
      <pubDate>Mon, 04 Oct 2021 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/multiple-linear-regression-made-simple/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#simple-linear-regression-reminder&#34; id=&#34;toc-simple-linear-regression-reminder&#34;&gt;Simple linear regression: reminder&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#principle&#34; id=&#34;toc-principle&#34;&gt;Principle&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#equation&#34; id=&#34;toc-equation&#34;&gt;Equation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#interpretations-of-coefficients-widehatbeta&#34; id=&#34;toc-interpretations-of-coefficients-widehatbeta&#34;&gt;Interpretations of coefficients &lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta\)&lt;/span&gt;&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#another-interpretation-of-the-intercept&#34; id=&#34;toc-another-interpretation-of-the-intercept&#34;&gt;Another interpretation of the intercept&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#significance-of-the-relationship&#34; id=&#34;toc-significance-of-the-relationship&#34;&gt;Significance of the relationship&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#correlation-does-not-imply-causation&#34; id=&#34;toc-correlation-does-not-imply-causation&#34;&gt;Correlation does not imply causation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conditions-of-application&#34; id=&#34;toc-conditions-of-application&#34;&gt;Conditions of application&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#visualizations&#34; id=&#34;toc-visualizations&#34;&gt;Visualizations&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#multiple-linear-regression&#34; id=&#34;toc-multiple-linear-regression&#34;&gt;Multiple linear regression&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#principle-1&#34; id=&#34;toc-principle-1&#34;&gt;Principle&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#equation-1&#34; id=&#34;toc-equation-1&#34;&gt;Equation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#interpretations-of-coefficients-widehatbeta-1&#34; id=&#34;toc-interpretations-of-coefficients-widehatbeta-1&#34;&gt;Interpretations of coefficients &lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta\)&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conditions-of-application-1&#34; id=&#34;toc-conditions-of-application-1&#34;&gt;Conditions of application&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#how-to-choose-a-good-linear-model&#34; id=&#34;toc-how-to-choose-a-good-linear-model&#34;&gt;How to choose a good linear model?&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#p-value-associated-to-the-model&#34; id=&#34;toc-p-value-associated-to-the-model&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(P\)&lt;/span&gt;-value associated to the model&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#coefficient-of-determination-r2&#34; id=&#34;toc-coefficient-of-determination-r2&#34;&gt;Coefficient of determination &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#parsimony&#34; id=&#34;toc-parsimony&#34;&gt;Parsimony&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#visualizations-1&#34; id=&#34;toc-visualizations-1&#34;&gt;Visualizations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#to-go-further&#34; id=&#34;toc-to-go-further&#34;&gt;To go further&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#print-models-parameters&#34; id=&#34;toc-print-models-parameters&#34;&gt;Print model’s parameters&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#automatic-reporting&#34; id=&#34;toc-automatic-reporting&#34;&gt;Automatic reporting&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#predictions&#34; id=&#34;toc-predictions&#34;&gt;Predictions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#linear-hypothesis-tests&#34; id=&#34;toc-linear-hypothesis-tests&#34;&gt;Linear hypothesis tests&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#overall-effect-of-categorical-variables&#34; id=&#34;toc-overall-effect-of-categorical-variables&#34;&gt;Overall effect of categorical variables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#interaction&#34; id=&#34;toc-interaction&#34;&gt;Interaction&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#summary&#34; id=&#34;toc-summary&#34;&gt;Summary&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;images/multiple-linear-regression.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;Remember that &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt; is a branch of statistics that allows to describe your data at hand.&lt;/p&gt;
&lt;p&gt;Inferential statistics (with the popular &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt; and confidence intervals) is another branch of statistics that allows to make inferences, that is, to draw conclusions about a population based on a &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;sample&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The last branch of statistics is about &lt;strong&gt;modeling the relationship between two or more variables&lt;/strong&gt;.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; The most common statistical tool to describe and evaluate the link between variables is linear regression.&lt;/p&gt;
&lt;p&gt;There are two types of linear regression:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;strong&gt;Simple linear regression&lt;/strong&gt; is a statistical approach that allows to assess the linear relationship between two &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#quantitative&#34;&gt;quantitative variables&lt;/a&gt;. More precisely, it enables the relationship to be quantified and its significance to be evaluated.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Multiple linear regression&lt;/strong&gt; is a generalization of simple linear regression, in the sense that this approach makes it possible to evaluate the linear relationships between a response variable (quantitative) and several explanatory variables (quantitative or &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;qualitative&lt;/a&gt;).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In the real world, multiple linear regression is used more frequently than simple linear regression. This is mostly the case because:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Multiple linear regression allows to evaluate the relationship between two variables, while &lt;strong&gt;controlling for the effect&lt;/strong&gt; (i.e., removing the effect) &lt;strong&gt;of other variables&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;With data collection becoming easier, more variables can be included and taken into account when analyzing data.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Multiple linear regression being such a powerful statistical tool, I would like to present it so that everyone understands it, and perhaps even use it when deemed necessary. However, I cannot afford to write about multiple linear regression without first presenting simple linear regression.&lt;/p&gt;
&lt;p&gt;So after a reminder about the principle and the interpretations that can be drawn from a simple linear regression, I will illustrate how to perform multiple linear regression in R. I will also show, in the context of multiple linear regression, how to interpret the output and discuss about its conditions of application. I will then conclude the article by presenting more advanced topics directly linked to linear regression.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;simple-linear-regression-reminder&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Simple linear regression: reminder&lt;/h1&gt;
&lt;p&gt;Simple linear regression is an asymmetric procedure in which:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;one of the variable is considered the response or the variable to be explained. It is also called &lt;strong&gt;dependent variable&lt;/strong&gt;, and is represented on the &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt;-axis&lt;/li&gt;
&lt;li&gt;the other variable is the explanatory or also called &lt;strong&gt;independent variable&lt;/strong&gt;, and is represented on the &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt;-axis&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Simple linear regression allows to &lt;strong&gt;evaluate the existence of a &lt;em&gt;linear&lt;/em&gt; relationship between two variables&lt;/strong&gt; and to quantify this link. Note that linearity is a strong assumption in linear regression in the sense that it tests and quantifies whether the two variables are &lt;em&gt;linearly&lt;/em&gt; dependent.&lt;/p&gt;
&lt;p&gt;What makes linear regression a powerful statistical tool is that it allows to &lt;strong&gt;quantify by what quantity the response/dependent variable varies when the explanatory/independent variable increases by one unit&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;This concept is key in linear regression and helps to answer the following questions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Is there a link between the amount spent in advertising and the sales during a certain period?&lt;/li&gt;
&lt;li&gt;Is the number of years of schooling valued, in financial terms, in the first job?&lt;/li&gt;
&lt;li&gt;Will an increase in tobacco taxes reduce its consumption?&lt;/li&gt;
&lt;li&gt;What is the most likely price of an apartment, depending on the area?&lt;/li&gt;
&lt;li&gt;Does a person’s reaction time to a stimulus depend on gender?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Simple linear regression can be seen as an extension to the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;analysis of variance (ANOVA)&lt;/a&gt; and the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test&lt;/a&gt;. ANOVA and t-test allow to compare groups in terms of a quantitative variable—2 groups for t-test and 3 or more groups for ANOVA.&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;For these tests, the independent variable, that is, the grouping variable forming the different groups to compare must be a qualitative variable. Linear regression is an extension because in addition to be used to compare groups, it is also used with quantitative independent variables (which is not possible with t-test and ANOVA).&lt;/p&gt;
&lt;p&gt;In this article, we are interested in assessing whether there is a linear relationship between the distance traveled with a gallon of fuel and the weight of cars. For this example, we use the &lt;code&gt;mtcars&lt;/code&gt; dataset (preloaded in R).&lt;/p&gt;
&lt;p&gt;The dataset includes fuel consumption and 10 aspects of automotive design and performance for 32 automobiles:&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;code&gt;mpg&lt;/code&gt; Miles/(US) gallon (with a gallon &lt;span class=&#34;math inline&#34;&gt;\(\approx\)&lt;/span&gt; 3.79 liters)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;cyl&lt;/code&gt; Number of cylinders&lt;/li&gt;
&lt;li&gt;&lt;code&gt;disp&lt;/code&gt; Displacement (cu.in.)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;hp&lt;/code&gt; Gross horsepower&lt;/li&gt;
&lt;li&gt;&lt;code&gt;drat&lt;/code&gt; Rear axle ratio&lt;/li&gt;
&lt;li&gt;&lt;code&gt;wt&lt;/code&gt; Weight (1000 lbs, with 1000 lbs &lt;span class=&#34;math inline&#34;&gt;\(\approx\)&lt;/span&gt; 453.59 kg)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;qsec&lt;/code&gt; 1/4 mile time (with 1/4 mile &lt;span class=&#34;math inline&#34;&gt;\(\approx\)&lt;/span&gt; 402.34 meters)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;vs&lt;/code&gt; Engine (0 = V-shaped, 1 = straight)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;am&lt;/code&gt; Transmission (0 = automatic, 1 = manual)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;gear&lt;/code&gt; Number of forward gears&lt;/li&gt;
&lt;li&gt;&lt;code&gt;carb&lt;/code&gt; Number of carburetors&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- mtcars

library(ggplot2)
ggplot(dat, aes(x = wt, y = mpg)) +
  geom_point() +
  labs(
    y = &amp;quot;Miles per gallon&amp;quot;,
    x = &amp;quot;Car&amp;#39;s weight (1000 lbs)&amp;quot;
  ) +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-1-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/#scatter-plot&#34;&gt;scatterplot&lt;/a&gt; above shows that there seems to be a &lt;strong&gt;negative relationship between the distance traveled with a gallon of fuel and the weight of a car&lt;/strong&gt;. This makes sense, as the heavier the car, the more fuel it consumes and thus the fewer miles it can drive with a gallon.&lt;/p&gt;
&lt;p&gt;This is already a good overview of the relationship between the two variables, but a simple linear regression with the miles per gallon as dependent variable and the car’s weight as independent variable goes further. It will tell us by &lt;strong&gt;how many miles the distance varies, on average, when the weight varies by one unit&lt;/strong&gt; (1000 lbs in this case). This is possible thanks to the regression line.&lt;/p&gt;
&lt;div id=&#34;principle&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Principle&lt;/h2&gt;
&lt;p&gt;The principle of simple linear regression is to &lt;strong&gt;find the line&lt;/strong&gt; (i.e., determine its equation) &lt;strong&gt;which passes as close as possible to the observations&lt;/strong&gt;, that is, the set of points formed by the pairs &lt;span class=&#34;math inline&#34;&gt;\((x_i, y_i)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;In the first step, there are many potential lines. Three of them are plotted:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-2-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;To find the line which passes as close as possible to all the points, we take the square of the vertical distance between each point and each potential line. Note that we take the square of the distances to make sure that a negative gap (i.e., a point below the line) is not compensated by a positive gap (i.e., a point above the line). The line which passes closest to the set of points is the one which &lt;strong&gt;&lt;em&gt;minimizes&lt;/em&gt;&lt;/strong&gt; &lt;strong&gt;the sum of these squared distances&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The resulting regression line is presented in blue in the following plot, and the dashed gray lines represent the vertical distance between the points and the fitted line. These vertical distances between each observed point and the fitted line determined by the least squares method are called the &lt;strong&gt;residuals&lt;/strong&gt; of the linear regression model and denoted &lt;span class=&#34;math inline&#34;&gt;\(\epsilon\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-3-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;By definition, there is no other line with a smaller total distance between the points and the line. This method is called the least squares method, or &lt;strong&gt;OLS&lt;/strong&gt; for &lt;strong&gt;ordinary least squares&lt;/strong&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;equation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Equation&lt;/h2&gt;
&lt;p&gt;The regression model can be written in the form of the equation:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[Y = \beta_0 + \beta_1 X + \epsilon\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;with:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; the dependent variable&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; the independent variable&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\beta_0\)&lt;/span&gt; the intercept (the mean value of &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; when &lt;span class=&#34;math inline&#34;&gt;\(x = 0\)&lt;/span&gt;), also sometimes denoted &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\beta_1\)&lt;/span&gt; the slope (the expected increase in &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; when &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; increases by one unit)&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\epsilon\)&lt;/span&gt; the residuals (the error term of mean 0 which describes the variations of &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; not captured by the model, also referred as the noise)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When we determine the line which passes closest to all the points (we say that we fit a line to the observed data), we actually &lt;strong&gt;estimate the unknown parameters &lt;span class=&#34;math inline&#34;&gt;\(\beta_0\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\beta_1\)&lt;/span&gt;&lt;/strong&gt; based on the data at hand. Remember from your geometry classes, to draw a line you only need two parameters—the intercept and the slope.&lt;/p&gt;
&lt;p&gt;These estimates (and thus the blue line shown in the previous scatterplot) can be computed by hand with the following formulas:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
\widehat\beta_1 &amp;amp;= \frac{\sum^n_{i = 1} (x_i - \bar{x})(y_i - \bar{y})}{\sum^n_{i = 1}(x_i - \bar{x})^2} \\
&amp;amp;= \frac{\left(\sum^n_{i = 1}x_iy_i\right) - n\bar{x}\bar{y}}{\sum^n_{i = 1}(x_i - \bar{x})^2}
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;and&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\widehat\beta_0 = \bar{y} - \widehat\beta_1 \bar{x}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;with &lt;span class=&#34;math inline&#34;&gt;\(\bar{x}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\bar{y}\)&lt;/span&gt; denoting the sample mean of &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt;, respectively.&lt;/p&gt;
&lt;p&gt;(If you struggle to compute &lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta_0\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta_1\)&lt;/span&gt; by hand, see this &lt;a href=&#34;https://statsandr.com/blog/a-shiny-app-for-simple-linear-regression-by-hand-and-in-r/&#34;&gt;Shiny app&lt;/a&gt; which helps you to easily find these estimates based on your data.)&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;interpretations-of-coefficients-widehatbeta&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Interpretations of coefficients &lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta\)&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;The &lt;strong&gt;intercept &lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta_0\)&lt;/span&gt;&lt;/strong&gt; is the &lt;strong&gt;mean value of the dependent variable &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; when the independent variable &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; takes the value 0&lt;/strong&gt;. Its estimation has no interest in evaluating whether there is a linear relationship between two variables. It has, however, an interest if you want to know what the mean value of &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; could be when &lt;span class=&#34;math inline&#34;&gt;\(x = 0\)&lt;/span&gt;.&lt;a href=&#34;#fn4&#34; class=&#34;footnote-ref&#34; id=&#34;fnref4&#34;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;slope &lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta_1\)&lt;/span&gt;&lt;/strong&gt;, on the other hand, corresponds to the expected &lt;strong&gt;variation of &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; when &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; varies by one unit&lt;/strong&gt;. It tells us two important informations:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;The &lt;strong&gt;sign of the slope&lt;/strong&gt; indicates the &lt;strong&gt;direction of the line&lt;/strong&gt;—a positive slope (&lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta_1 &amp;gt; 0\)&lt;/span&gt;) indicates that there is a positive relationship between the two variables of interest (they vary in the same direction), whereas a negative slope (&lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta_1 &amp;lt; 0\)&lt;/span&gt;) means that there is a negative relationship between the two variables (they vary in opposite directions).&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;value of the slope&lt;/strong&gt; provides information on the &lt;strong&gt;speed of evolution&lt;/strong&gt; of the variable &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; as a function of the variable &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt;. The larger the slope in absolute value, the larger the expected variation of &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; for each unit of &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt;. Note, however, that a large value does not necessarily mean that the relationship is statistically significant (more on that in the section about &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#significance-of-the-relationship&#34;&gt;significance of the relationship&lt;/a&gt;).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This is similar to the &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;correlation coefficient&lt;/a&gt;, which gives information about the direction and the strength of the relationship between two variables.&lt;/p&gt;
&lt;p&gt;To perform a linear regression in R, we use the &lt;code&gt;lm()&lt;/code&gt; function (which stands for linear model). The function requires to set the dependent variable first then the independent variable, separated by a tilde (&lt;code&gt;~&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;Applied to our example of weight and car’s consumption, we have:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;model &amp;lt;- lm(mpg ~ wt, data = dat)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;summary()&lt;/code&gt; function gives the results of the model:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(model)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
## lm(formula = mpg ~ wt, data = dat)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -4.5432 -2.3647 -0.1252  1.4096  6.8727 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(&amp;gt;|t|)    
## (Intercept)  37.2851     1.8776  19.858  &amp;lt; 2e-16 ***
## wt           -5.3445     0.5591  -9.559 1.29e-10 ***
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 
## Residual standard error: 3.046 on 30 degrees of freedom
## Multiple R-squared:  0.7528,	Adjusted R-squared:  0.7446 
## F-statistic: 91.38 on 1 and 30 DF,  p-value: 1.294e-10&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In practice, we usually check the conditions of application &lt;em&gt;before&lt;/em&gt; interpreting the coefficients (because if they are not respected, results may be biased).&lt;/p&gt;
&lt;p&gt;In this article, however, I present the interpretations before testing the conditions because the point is to show how to interpret the results, and less about finding a valid model.&lt;/p&gt;
&lt;p&gt;The results can be summarized as follows (see the column &lt;code&gt;Estimate&lt;/code&gt; in the table &lt;code&gt;Coefficients&lt;/code&gt;):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The intercept &lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta_0 =\)&lt;/span&gt; 37.29 indicates that, for a hypothetical car weighting 0 lbs, we can expect, on average, a consumption of 37.29 miles/gallon. This interpretation is shown for illustrative purposes, but as a car weighting 0 lbs is impossible, the interpretation has no meaning. In practice, we would therefore refrain from interpreting the intercept in this case. See another interpretation of the intercept when the independent variable is centered around its mean in this &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#another-interpretation-of-the-intercept&#34;&gt;section&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;The slope &lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta_1 =\)&lt;/span&gt; -5.34 indicates that:
&lt;ul&gt;
&lt;li&gt;There is a &lt;strong&gt;negative relationship&lt;/strong&gt; between the weight and the distance a car can drive with a gallon (this was expected given the negative trend of the points in the scatterplot shown previously).&lt;/li&gt;
&lt;li&gt;But more importantly, a slope of -5.34 means that, for an increase of one unit in the weight (that is, an increase of 1000 lbs), the number of miles per gallon decreases, on average, by 5.34 units. In other words, &lt;strong&gt;for an increase of 1000 lbs, the number of miles/gallon decreases, on average, by 5.34&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&#34;another-interpretation-of-the-intercept&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Another interpretation of the intercept&lt;/h3&gt;
&lt;p&gt;Another useful interpretation of the intercept is when the independent variable is centered around its mean. In this case, the intercept is interpreted as the mean value of &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; for individuals who have a value of &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; equal to the mean of &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Let’s see it in practice.&lt;/p&gt;
&lt;p&gt;We first center the &lt;code&gt;wt&lt;/code&gt; variable around the mean then rerun a simple linear model with this new variable:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat_centered &amp;lt;- dat

dat_centered$wt_centered &amp;lt;- dat$wt - mean(dat$wt)

mod_centered &amp;lt;- lm(mpg ~ wt_centered,
  data = dat_centered
)

summary(mod_centered)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
## lm(formula = mpg ~ wt_centered, data = dat_centered)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -4.5432 -2.3647 -0.1252  1.4096  6.8727 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(&amp;gt;|t|)    
## (Intercept)  20.0906     0.5384  37.313  &amp;lt; 2e-16 ***
## wt_centered  -5.3445     0.5591  -9.559 1.29e-10 ***
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 
## Residual standard error: 3.046 on 30 degrees of freedom
## Multiple R-squared:  0.7528,	Adjusted R-squared:  0.7446 
## F-statistic: 91.38 on 1 and 30 DF,  p-value: 1.294e-10&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Based on the results, we see that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The slope has not changed, the interpretation is the same than without the centering (which makes sense since the regression line has simply been shifted to the right or left).&lt;/li&gt;
&lt;li&gt;More importantly, the intercept is now &lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta_0 =\)&lt;/span&gt; 20.09, so we can expect, on average, a consumption of 20.09 miles/gallon for a car with an average weight (the mean of weight is 3.22 so 3220 lbs).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This centering is particularly interesting:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;when the continuous independent variable has &lt;strong&gt;no&lt;/strong&gt; meaningful value of 0 (which is the case here as a car with a weight of 0 lbs is not meaningful), or&lt;/li&gt;
&lt;li&gt;when interpreting the intercept is important.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that centering does not have to be done around the mean only. The independent variable can also be centered at some value that is actually in the range of the data. The exact value you center on does not matter as long it’s meaningful and within the range of data (it is not recommended to center it on a value that is not in the range of the data because we are not sure about the type of relationship between the two variables outside that range).&lt;/p&gt;
&lt;p&gt;For our example, we may find that choosing the lowest value or the highest value of weight is the best option. So it’s up to us to decide the weight at which it’s most meaningful to interpret the intercept.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;significance-of-the-relationship&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Significance of the relationship&lt;/h2&gt;
&lt;p&gt;As mentioned earlier, the &lt;strong&gt;value of the slope does not&lt;/strong&gt;, by itself, make it possible to &lt;strong&gt;assess the significance of the linear relationship&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In other words, a slope different from 0 does not necessarily mean it is &lt;em&gt;significantly&lt;/em&gt; different from 0, so it does not mean that there is a &lt;strong&gt;significant&lt;/strong&gt; relationship between the two variables in the population. There could be a slope of 10 that is not significant, and a slope of 2 that is significant.&lt;/p&gt;
&lt;p&gt;Significance of the relationship also depends on the variability of the slope, which is measured by its standard error and generally noted &lt;span class=&#34;math inline&#34;&gt;\(se(\widehat\beta_1)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Without going too much into details, to assess the significance of the linear relationship, we divide the slope by its standard error. This ratio is the test statistic and follows a Student distribution with &lt;span class=&#34;math inline&#34;&gt;\(n - 2\)&lt;/span&gt; degrees of freedom:&lt;a href=&#34;#fn5&#34; class=&#34;footnote-ref&#34; id=&#34;fnref5&#34;&gt;&lt;sup&gt;5&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[T_{n - 2} = \frac{\widehat\beta_1}{se(\widehat\beta_1)}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For a bilateral test, the null and alternative hypotheses are:&lt;a href=&#34;#fn6&#34; class=&#34;footnote-ref&#34; id=&#34;fnref6&#34;&gt;&lt;sup&gt;6&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0 : \beta_1 = 0\)&lt;/span&gt; (there is no (linear) relationship between the two variables)&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1 : \beta_1 \ne 0\)&lt;/span&gt; (there is a (linear) relationship between the two variables)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Roughly speaking, if this ratio is greater than 2 in absolute value then the slope is significantly different from 0, and therefore the relationship between the two variables is significant (and in that case it is positive or negative depending on the sign of the estimate &lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta_1\)&lt;/span&gt;).&lt;/p&gt;
&lt;p&gt;The standard error and the test statistic are shown in the column &lt;code&gt;Std. Error&lt;/code&gt; and &lt;code&gt;t value&lt;/code&gt; in the table &lt;code&gt;Coefficients&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Fortunately, R gives a more precise and easier way to assess to the significance of the relationship. The information is provided in the column &lt;code&gt;Pr(&amp;gt;|t|)&lt;/code&gt; of the &lt;code&gt;Coefficients&lt;/code&gt; table. This is the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/#a-note-on-p-value-and-significance-level-alpha&#34;&gt;&lt;em&gt;p&lt;/em&gt;-value&lt;/a&gt; of the test. As for any &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical test&lt;/a&gt;, if the &lt;em&gt;p&lt;/em&gt;-value is greater than or equal to the significance level (usually &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;), we do not reject the null hypothesis, and if the &lt;em&gt;p&lt;/em&gt;-value is lower than the significance level, we reject the null hypothesis.&lt;/p&gt;
&lt;p&gt;If we do not reject the null hypothesis, we do not reject the hypothesis of no relationship between the two variables (because we do not reject the hypothesis of a slope of 0). On the contrary, if we reject the null hypothesis of no relationship, we can conclude that there is a significant linear relationship between the two variables.&lt;/p&gt;
&lt;p&gt;In our example, the &lt;em&gt;p&lt;/em&gt;-value = 1.29e-10 &amp;lt; 0.05 so we reject the null hypothesis at the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 5\%\)&lt;/span&gt;. We therefore conclude that there is a &lt;strong&gt;significant relationship between a car’s weight and its fuel consumption&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Tip:&lt;/em&gt; In order to make sure I interpret only parameters that are significant, I tend to first check the significance of the parameters thanks to the &lt;em&gt;p&lt;/em&gt;-values, and then interpret the estimates accordingly. For completeness, note that the test is also performed on the intercept. The &lt;em&gt;p&lt;/em&gt;-value being smaller than 0.05, we also conclude that the intercept is significantly different from 0.&lt;/p&gt;
&lt;div id=&#34;correlation-does-not-imply-causation&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Correlation does not imply causation&lt;/h3&gt;
&lt;p&gt;Be careful that a significant relationship between two variables does not necessarily mean that there is an influence of one variable on the other or that there is a causal effect between these two variables!&lt;/p&gt;
&lt;p&gt;A significant relationship between &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; can appear in several cases:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; causes &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; causes &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;a third variable cause &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;a combination of these three reasons&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A statistical model alone cannot establish a causal link between two variables. Demonstrating causality between two variables is more complex and requires, among others, a specific experimental design, the repeatability of the results over time, as well as various samples.&lt;/p&gt;
&lt;p&gt;This is the reason you will often read “&lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/#correlation-does-not-imply-causation&#34;&gt;Correlation does not imply causation&lt;/a&gt;” and linear regression follows the same principle.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conditions-of-application&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Conditions of application&lt;/h2&gt;
&lt;p&gt;Unfortunately, linear regression cannot be used in all situations.&lt;/p&gt;
&lt;p&gt;In addition to the requirement that the dependent variable must be a continuous quantitative variables, simple linear regression requires that the data satisfy the following conditions:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;strong&gt;Linearity:&lt;/strong&gt; The relationship between the two variables should be linear (at least roughly). For this reason it is always necessary to represent graphically the data with a scatterplot before performing a simple linear regression.&lt;a href=&#34;#fn7&#34; class=&#34;footnote-ref&#34; id=&#34;fnref7&#34;&gt;&lt;sup&gt;7&lt;/sup&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-7-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;ol start=&#34;2&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;strong&gt;Independence:&lt;/strong&gt; Observations must be independent. It is the sampling plan and the experimental design that usually provide information on this condition. If the data come from different individuals or experimental units, they are usually independent. On the other hand, if the same individuals are measured at different periods, the data are probably not independent.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Normality of the residuals:&lt;/strong&gt; For large sample sizes, confidence intervals and tests on the coefficients are (approximately) valid whether the error follows a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution&lt;/a&gt; or not (a consequence of the central limit theorem, see more in &lt;span class=&#34;citation&#34;&gt;Ernst and Albers (&lt;a href=&#34;#ref-ernst2017regression&#34;&gt;2017&lt;/a&gt;)&lt;/span&gt; and &lt;span class=&#34;citation&#34;&gt;Lumley et al. (&lt;a href=&#34;#ref-lumley2002importance&#34;&gt;2002&lt;/a&gt;)&lt;/span&gt;)! For small sample sizes, residuals should follow a normal distribution. This condition can be tested visually (via a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#qq-plot&#34;&gt;QQ-plot&lt;/a&gt; and/or a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt;), or more formally (via the &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#normality-test&#34;&gt;Shapiro-Wilk test&lt;/a&gt; for instance).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Homoscedasticity of the residuals:&lt;/strong&gt; The variance of the errors should be constant. There is a lack of homoscedasticity when the dispersion of the residuals increases with the predicted values (fitted values). This condition can be tested visually (by plotting the standardized residuals vs. the fitted values) or more formally (via the Breusch-Pagan test).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No influential points:&lt;/strong&gt; If the data contain &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt;, it is essential to identify them so that they &lt;strong&gt;do not&lt;/strong&gt;, on their own, &lt;strong&gt;influence&lt;/strong&gt; the results of the regression. Note that an outlier is not an issue &lt;em&gt;per se&lt;/em&gt; if the point is in the alignment of the regression line for example because it does not influence the regression line. It becomes a problem in the context of linear regression if it influences in a substantial manner the estimates (and in particular the slope of the regression line). This can be tackled by identifying outliers (via the Cook’s distance&lt;a href=&#34;#fn8&#34; class=&#34;footnote-ref&#34; id=&#34;fnref8&#34;&gt;&lt;sup&gt;8&lt;/sup&gt;&lt;/a&gt; or the leverage index&lt;a href=&#34;#fn9&#34; class=&#34;footnote-ref&#34; id=&#34;fnref9&#34;&gt;&lt;sup&gt;9&lt;/sup&gt;&lt;/a&gt; for instance), and comparing the results with and without the potential outliers. Do the results remain the same with the two approaches? If yes, outliers are not really an issue in this case. If results are much different, you can use the Theil-Sen estimator, robust regression or quantile regression which are all more robust to outliers.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;em&gt;Tip:&lt;/em&gt; I remember the first 4 conditions thanks to the acronym “LINE”, for Linearity, Independence, Normality and Equality of variance.&lt;/p&gt;
&lt;p&gt;If any of the condition is not met, the tests and the conclusions could be erroneous so it is best to avoid using and interpreting the model. If this is the case, sometimes the conditions can be met by transforming the data (e.g., logarithmic transformation, square or square root, Box-Cox transformation, etc.) or by adding a quadratic or cubic (or even a higher-order polynomial) term to the model.&lt;/p&gt;
&lt;p&gt;If it does not help, it could be worth thinking about removing some variables or adding other variables, or even considering other types of models such as non-linear models.&lt;/p&gt;
&lt;p&gt;Keep in mind that in practice, &lt;strong&gt;conditions of application should be verified before drawing any conclusion&lt;/strong&gt; based on the model. I refrain here from testing the conditions on our data because it will be covered in details in the context of multiple linear regression (see this &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#conditions-of-application-1&#34;&gt;section&lt;/a&gt;).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;visualizations&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Visualizations&lt;/h2&gt;
&lt;p&gt;If you are a frequent reader of the blog, you may know that I like to draw (simple but efficient) &lt;a href=&#34;https://statsandr.com/tags/visualization/&#34;&gt;visualizations&lt;/a&gt; to illustrate my statistical analyses. Linear regression is not an exception.&lt;/p&gt;
&lt;p&gt;There are numerous ways to visualize the relationship between the two variables of interest, but the easiest one I found so far is via the &lt;code&gt;visreg()&lt;/code&gt; function from the package of the same name:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(visreg)
visreg(model)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-8-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;I like this approach for its simplicity—only a single line of code.&lt;/p&gt;
&lt;p&gt;However, other elements could be displayed on the regression plot (for example the regression equation and the &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt;). This can easily be done with the &lt;code&gt;stat_regline_equation()&lt;/code&gt; and &lt;code&gt;stat_cor()&lt;/code&gt; functions from the &lt;code&gt;{ggpubr}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load necessary libraries
library(ggpubr)

# create plot with regression line, regression equation and R^2
ggplot(dat, aes(x = wt, y = mpg)) +
  geom_smooth(method = &amp;quot;lm&amp;quot;) +
  geom_point() +
  stat_regline_equation(label.x = 3, label.y = 32) + # for regression equation
  stat_cor(aes(label = after_stat(rr.label)), label.x = 3, label.y = 30) + # for R^2
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-9-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;multiple-linear-regression&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Multiple linear regression&lt;/h1&gt;
&lt;p&gt;Now that you understand the principle behind simple linear regression and you know how to interpret the results, it is time to discuss about multiple linear regression.&lt;/p&gt;
&lt;p&gt;We also start with the underlying principle of multiple linear regression, then show how to interpret the results, how to test the conditions of application and finish with more advanced topics.&lt;/p&gt;
&lt;div id=&#34;principle-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Principle&lt;/h2&gt;
&lt;p&gt;Multiple linear regression is a generalization of simple linear regression, in the sense that this approach makes it possible to relate one variable with &lt;strong&gt;several variables&lt;/strong&gt; through a linear function in its parameters.&lt;/p&gt;
&lt;p&gt;Multiple linear regression is used to assess the relationship between two variables &lt;strong&gt;while taking into account the effect of other variables&lt;/strong&gt;. By taking into account the effect of other variables, we cancel out the effect of these other variables in order to &lt;strong&gt;isolate&lt;/strong&gt; and measure the relationship between the two variables of interest. This point is the main difference with simple linear regression.&lt;/p&gt;
&lt;p&gt;To illustrate how to perform a multiple linear regression in R, we use the same dataset than the one used for simple linear regression (&lt;code&gt;mtcars&lt;/code&gt;). Below a short preview:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;head(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We have seen that there is a significant and negative linear relationship between the distance a car can drive with a gallon and its weight (&lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta_1 =\)&lt;/span&gt; -5.34, &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &amp;lt; 0.001).&lt;/p&gt;
&lt;p&gt;However, one may wonder whether there are not in reality other factors that could explain a car’s fuel consumption.&lt;/p&gt;
&lt;p&gt;To explore this, we can visualize the relationship between a car’s fuel consumption (&lt;code&gt;mpg&lt;/code&gt;) together with its weight (&lt;code&gt;wt&lt;/code&gt;), horsepower (&lt;code&gt;hp&lt;/code&gt;) and displacement (&lt;code&gt;disp&lt;/code&gt;) (engine displacement is the combined swept (or displaced) volume of air resulting from the up-and-down movement of pistons in the cylinders, usually the higher the more powerful the car):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = wt, y = mpg, colour = hp, size = disp) +
  geom_point() +
  scale_color_gradient() +
  labs(
    y = &amp;quot;Miles per gallon&amp;quot;,
    x = &amp;quot;Weight (1000 lbs)&amp;quot;,
    color = &amp;quot;Horsepower&amp;quot;,
    size = &amp;quot;Displacement&amp;quot;
  ) +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-11-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;It seems that, in addition to the negative relationship between miles per gallon and weight, there is also:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a negative relationship between miles/gallon and horsepower (lighter points, indicating more horsepower, tend to be more present in low levels of miles per gallon)&lt;/li&gt;
&lt;li&gt;a negative relationship between miles/gallon and displacement (bigger points, indicating larger values of displacement, tend to be more present in low levels of miles per gallon).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Therefore, we would like to evaluate the relation between the fuel consumption and the weight, but this time by adding information on the horsepower and displacement. By adding this additional information, we are able to &lt;strong&gt;capture only the direct relationship between miles/gallon and weight&lt;/strong&gt; (the indirect effect due to horsepower and displacement is canceled out).&lt;/p&gt;
&lt;p&gt;This is the whole point of multiple linear regression! In fact, in multiple linear regression, the estimated relationship between the dependent variable and an explanatory variable is an &lt;strong&gt;adjusted&lt;/strong&gt; relationship, that is, free of the linear effects of the other explanatory variables.&lt;/p&gt;
&lt;p&gt;Let’s illustrate this notion of adjustment by adding both horsepower and displacement in our linear regression model:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;model2 &amp;lt;- lm(mpg ~ wt + hp + disp,
  data = dat
)

summary(model2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
## lm(formula = mpg ~ wt + hp + disp, data = dat)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -3.891 -1.640 -0.172  1.061  5.861 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(&amp;gt;|t|)    
## (Intercept) 37.105505   2.110815  17.579  &amp;lt; 2e-16 ***
## wt          -3.800891   1.066191  -3.565  0.00133 ** 
## hp          -0.031157   0.011436  -2.724  0.01097 *  
## disp        -0.000937   0.010350  -0.091  0.92851    
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 
## Residual standard error: 2.639 on 28 degrees of freedom
## Multiple R-squared:  0.8268,	Adjusted R-squared:  0.8083 
## F-statistic: 44.57 on 3 and 28 DF,  p-value: 8.65e-11&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can see that now, the relationship between miles/gallon and weight is weaker in terms of slope (&lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta_1 =\)&lt;/span&gt; -3.8 now, against &lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta_1 =\)&lt;/span&gt; -5.34 when only the weight was considered).&lt;/p&gt;
&lt;p&gt;The effect of weight on fuel consumption was adjusted according to the effect of horsepower and displacement. This is the remaining effect between miles/gallon and weight after the effects of horsepower and displacement have been taken into account. More detailed interpretations in this &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#interpretations-of-coefficients-widehatbeta-1&#34;&gt;section&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;equation-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Equation&lt;/h2&gt;
&lt;p&gt;Multiple linear regression models are defined by the equation&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[Y = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \dots + \beta_p X_p + \epsilon\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;It is similar than the equation of simple linear regression, except that there is more than one independent variables (&lt;span class=&#34;math inline&#34;&gt;\(X_1, X_2, \dots, X_p\)&lt;/span&gt;).&lt;/p&gt;
&lt;p&gt;Estimation of the parameters &lt;span class=&#34;math inline&#34;&gt;\(\beta_0, \dots, \beta_p\)&lt;/span&gt; by the method of least squares is based on the same principle as that of simple linear regression, but applied to &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt; dimensions. It is thus no longer a question of finding the best line (the one which passes closest to the pairs of points (&lt;span class=&#34;math inline&#34;&gt;\(y_i, x_i\)&lt;/span&gt;)), but finding the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-dimensional plane which passes closest to the coordinate points (&lt;span class=&#34;math inline&#34;&gt;\(y_i, x_{i1}, \dots, x_{ip}\)&lt;/span&gt;).&lt;/p&gt;
&lt;p&gt;This is done by &lt;strong&gt;&lt;em&gt;minimizing&lt;/em&gt; the sum of the squares of the deviations of the points on the plane&lt;/strong&gt;:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;images/multiple-linear-regression-plane.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Source: James, G., Witten, D., Hastie, T., &amp;amp; Tibshirani, R. (2013)&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Source: James, G., Witten, D., Hastie, T., &amp;amp; Tibshirani, R. (2013)&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;interpretations-of-coefficients-widehatbeta-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Interpretations of coefficients &lt;span class=&#34;math inline&#34;&gt;\(\widehat\beta\)&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;The least squares method results in an adjusted estimate of the coefficients. The term adjusted means &lt;strong&gt;after taking into account the linear effects&lt;/strong&gt; of the other independent variables on the dependent variable, but also on the predictor variable.&lt;/p&gt;
&lt;p&gt;In other words, the coefficient &lt;span class=&#34;math inline&#34;&gt;\(\beta_1\)&lt;/span&gt; corresponds to the slope of the relationship between &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(X_1\)&lt;/span&gt; when the linear effects of the other explanatory variables (&lt;span class=&#34;math inline&#34;&gt;\(X_2, \dots, X_p\)&lt;/span&gt;) have been removed, both at the level of the dependent variable &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; but also at the level of &lt;span class=&#34;math inline&#34;&gt;\(X_1\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Applied to our model with weight, horsepower and displacement as independent variables, we have:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(model2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
## lm(formula = mpg ~ wt + hp + disp, data = dat)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -3.891 -1.640 -0.172  1.061  5.861 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(&amp;gt;|t|)    
## (Intercept) 37.105505   2.110815  17.579  &amp;lt; 2e-16 ***
## wt          -3.800891   1.066191  -3.565  0.00133 ** 
## hp          -0.031157   0.011436  -2.724  0.01097 *  
## disp        -0.000937   0.010350  -0.091  0.92851    
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 
## Residual standard error: 2.639 on 28 degrees of freedom
## Multiple R-squared:  0.8268,	Adjusted R-squared:  0.8083 
## F-statistic: 44.57 on 3 and 28 DF,  p-value: 8.65e-11&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The table &lt;code&gt;Coefficients&lt;/code&gt; gives the estimate for each parameter (column &lt;code&gt;Estimate&lt;/code&gt;), together with the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value of the nullity of the parameter (column &lt;code&gt;Pr(&amp;gt;|t|)&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;The hypotheses are the same as for simple linear regression, that is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0 : \beta_j = 0\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1 : \beta_j \ne 0\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The test of &lt;span class=&#34;math inline&#34;&gt;\(\beta_j = 0\)&lt;/span&gt; is equivalent to testing the hypothesis: is the dependent variable associated with the independent variable studied, all other things being equal, that is to say, at constant level of the other independent variables.&lt;/p&gt;
&lt;p&gt;In other words:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the test of &lt;span class=&#34;math inline&#34;&gt;\(\beta_1 = 0\)&lt;/span&gt; corresponds to testing the hypothesis: is fuel consumption associated with a car’s weight, at a constant level of horsepower and displacement&lt;/li&gt;
&lt;li&gt;the test of &lt;span class=&#34;math inline&#34;&gt;\(\beta_2 = 0\)&lt;/span&gt; corresponds to testing the hypothesis: is fuel consumption associated with horsepower, at a constant level of weight and displacement&lt;/li&gt;
&lt;li&gt;the test of &lt;span class=&#34;math inline&#34;&gt;\(\beta_3 = 0\)&lt;/span&gt; corresponds to testing the hypothesis: is fuel consumption associated with displacement, at a constant level of weight and horsepower&lt;/li&gt;
&lt;li&gt;(for the sake of completeness: the test of &lt;span class=&#34;math inline&#34;&gt;\(\beta_0 = 0\)&lt;/span&gt; corresponds to testing the hypothesis: is miles/gallon different from 0 when weight, horsepower and displacement are equal to 0)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In practice, we usually check the conditions of application &lt;em&gt;before&lt;/em&gt; interpreting the coefficients (because if they are not respected, results may be biased). In this article, however, I present the interpretations before testing the conditions because the point is to show how to interpret the results, and less about finding a valid model.&lt;/p&gt;
&lt;p&gt;Based on the output of our model, we conclude that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;There is a significant and negative relationship between miles/gallon and weight, &lt;strong&gt;all else being equal&lt;/strong&gt;. So for an increase of one unit in the weight (that is, an increase of 1000 lbs), the number of miles/gallon decreases, on average, by 3.8, for a constant level of horsepower and displacement (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.001).&lt;/li&gt;
&lt;li&gt;There is a significant and negative relationship between miles/gallon and horsepower, all else being equal. So for an increase of one unit of horsepower, the distance traveled with a gallon decreases, on average, by 0.03 mile, for a constant level of weight and displacement (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.011).&lt;/li&gt;
&lt;li&gt;We do not reject the hypothesis of no relationship between miles/gallon and displacement when weight and horsepower stay constant (because &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.929 &amp;gt; 0.05).&lt;/li&gt;
&lt;li&gt;(For completeness but it should be interpreted only when it makes sense: for a weight, horsepower and displacement = 0, we can expect that a car has, on average, a fuel consumption of 37.11 miles/gallon (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &amp;lt; 0.001). See a more useful interpretation of the intercept when the independent variables are centered in this &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#another-interpretation-of-the-intercept&#34;&gt;section&lt;/a&gt;.)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This is how to interpret quantitative independent variables. &lt;strong&gt;Interpreting qualitative independent variables&lt;/strong&gt; is slightly different in the sense that it quantifies the effect of a level in comparison with the reference level, sill all else being equal.&lt;/p&gt;
&lt;p&gt;So it compares the different groups (formed by the different levels of the categorical variable) in terms of the dependent variable (this is why linear regression can be seen as an extension to the t-test and ANOVA).&lt;/p&gt;
&lt;p&gt;For the illustration, we model the fuel consumption (&lt;code&gt;mpg&lt;/code&gt;) on the weight (&lt;code&gt;wt&lt;/code&gt;) and the shape of the engine (&lt;code&gt;vs&lt;/code&gt;). The variable &lt;code&gt;vs&lt;/code&gt; has two levels: V-shaped (the &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/#change-reference-level&#34;&gt;reference level&lt;/a&gt;) and straight engine.&lt;a href=&#34;#fn10&#34; class=&#34;footnote-ref&#34; id=&#34;fnref10&#34;&gt;&lt;sup&gt;10&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Recoding dat$vs
library(forcats)
dat$vs &amp;lt;- as.character(dat$vs)
dat$vs &amp;lt;- fct_recode(dat$vs,
  &amp;quot;V-shaped&amp;quot; = &amp;quot;0&amp;quot;,
  &amp;quot;Straight&amp;quot; = &amp;quot;1&amp;quot;
)

model3 &amp;lt;- lm(mpg ~ wt + vs,
  data = dat
)

summary(model3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
## lm(formula = mpg ~ wt + vs, data = dat)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -3.7071 -2.4415 -0.3129  1.4319  6.0156 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(&amp;gt;|t|)    
## (Intercept)  33.0042     2.3554  14.012 1.92e-14 ***
## wt           -4.4428     0.6134  -7.243 5.63e-08 ***
## vsStraight    3.1544     1.1907   2.649   0.0129 *  
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 
## Residual standard error: 2.78 on 29 degrees of freedom
## Multiple R-squared:  0.801,	Adjusted R-squared:  0.7873 
## F-statistic: 58.36 on 2 and 29 DF,  p-value: 6.818e-11&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Based on the output of our model, we conclude that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;For a V-shaped engine and for an increase of one unit in the weight (that is, an increase of 1000 lbs), the number of miles/gallon decreases, on average, by 4.44 (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &amp;lt; 0.001).&lt;/li&gt;
&lt;li&gt;The distance traveled with a gallon of fuel increases by, on average, 3.15 miles &lt;strong&gt;when the engine is straight compared to a V-shaped engine&lt;/strong&gt;, for a constant weight (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.013).&lt;/li&gt;
&lt;li&gt;(For completeness but it should be interpreted only when it makes sense: for a weight = 0 and a V-shaped engine, we can expect that the car has, on average, a fuel consumption of 33 miles/gallon (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &amp;lt; 0.001). See a more useful interpretation of the intercept when the independent variables are centered in this &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#another-interpretation-of-the-intercept&#34;&gt;section&lt;/a&gt;.)&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;conditions-of-application-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Conditions of application&lt;/h2&gt;
&lt;p&gt;As for simple linear regression, multiple linear regression requires some conditions of application for the model to be usable and the results to be interpretable. Conditions for simple linear regression also apply to multiple linear regression, that is:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;strong&gt;Linearity&lt;/strong&gt; of the relationships between the dependent and independent variables&lt;a href=&#34;#fn11&#34; class=&#34;footnote-ref&#34; id=&#34;fnref11&#34;&gt;&lt;sup&gt;11&lt;/sup&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Independence&lt;/strong&gt; of the observations&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Normality&lt;/strong&gt; of the residuals&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Homoscedasticity&lt;/strong&gt; of the residuals&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No influential points&lt;/strong&gt; (&lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt;)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;But there is one more condition for multiple linear regression:&lt;/p&gt;
&lt;ol start=&#34;6&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;strong&gt;No multicollinearity:&lt;/strong&gt; Multicollinearity arises when there is a strong linear &lt;strong&gt;&lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;correlation&lt;/a&gt; between the independent variables&lt;/strong&gt;, conditional on the other variables in the model. It is important to check it because it may lead to an imprecision or an instability of the estimated parameters when a variable changes. It can be assessed by studying the correlation between each pair of independent variables, or even better, by computing the variance inflation factor (VIF). The VIF measures how much the variance of an estimated regression coefficient increases, relative to a situation in which the explanatory variables are strictly independent. A high value of VIF is a sign of multicollinearity (the threshold is generally admitted at 5 or 10 depending on the domain). The easiest way to reduce the VIF is to remove some correlated independent variables, or eventually to &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/#scale&#34;&gt;standardize&lt;/a&gt; the data.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;You will often see that these conditions are verified by running &lt;code&gt;plot(model, which = 1:6)&lt;/code&gt; and it is totally correct. However, I recently discovered the &lt;code&gt;check_model()&lt;/code&gt; function from the &lt;code&gt;{performance}&lt;/code&gt; package which tests these conditions all at the same time (and let’s be honest, in a more elegant way).&lt;a href=&#34;#fn12&#34; class=&#34;footnote-ref&#34; id=&#34;fnref12&#34;&gt;&lt;sup&gt;12&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Applied on our &lt;code&gt;model2&lt;/code&gt; with miles/gallon as dependent variable, and weight, horsepower and displacement as independent variables, we have:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# install.packages(&amp;quot;performance&amp;quot;)
# install.packages(&amp;quot;see&amp;quot;)
library(performance)

check_model(model2)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-15-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In addition to testing all conditions at the same time, it also gives insight on how to interpret the different diagnostic plots and what you should expect (see in the subtitles of each plot).&lt;/p&gt;
&lt;p&gt;Based on these diagnostic plots, we see that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Homogeneity of variance (middle left plot) is respected&lt;/li&gt;
&lt;li&gt;Multicollinearity (bottom left plot) is not an issue (I tend to use the threshold of 10 for VIF, and all of them are below 10)&lt;a href=&#34;#fn13&#34; class=&#34;footnote-ref&#34; id=&#34;fnref13&#34;&gt;&lt;sup&gt;13&lt;/sup&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;There is no influential points (middle right plot)&lt;/li&gt;
&lt;li&gt;Normality of the residuals (bottom right plot) is also not perfect due to 3 points deviating from the reference line but it still seems acceptable to me. In any case, the number of observations is large enough given the number of parameters&lt;a href=&#34;#fn14&#34; class=&#34;footnote-ref&#34; id=&#34;fnref14&#34;&gt;&lt;sup&gt;14&lt;/sup&gt;&lt;/a&gt; and given the small deviation from normality so tests on the coefficients are (approximately) valid whether the error follows a normal distribution or not&lt;/li&gt;
&lt;li&gt;Linearity (top right plot) is not perfect so let’s check each independent variable separately:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# weight
ggplot(dat, aes(x = wt, y = mpg)) +
  geom_point() +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-16-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# horsepower
ggplot(dat, aes(x = hp, y = mpg)) +
  geom_point() +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-16-2.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# displacement
ggplot(dat, aes(x = disp, y = mpg)) +
  geom_point() +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-16-3.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;It seems that the relationship between miles/gallon and horsepower is not linear, which could be the main component of the slight linearity defect of the model.&lt;/p&gt;
&lt;p&gt;To improve linearity, the variable could be removed, a transformation could be applied (logarithmic and/or squared for instance) or a quadratic or cubic (or even a higher-order polynomial) term could be added to the model.&lt;a href=&#34;#fn15&#34; class=&#34;footnote-ref&#34; id=&#34;fnref15&#34;&gt;&lt;sup&gt;15&lt;/sup&gt;&lt;/a&gt; If this does not fix the issue of linearity, other types of models could be considered.&lt;/p&gt;
&lt;p&gt;If you want to read more about these conditions of applications and how to deal with them, here is a very complete &lt;a href=&#34;http://quantpsych.net/stats_modeling/diagnostics.html&#34;&gt;chapter&lt;/a&gt; on diagnostics for linear models written by Prof. Dustin Fife.&lt;/p&gt;
&lt;p&gt;For the sake of easiness and for illustrative purposes, we assume linearity for the rest of the article.&lt;/p&gt;
&lt;p&gt;When the conditions of application are met, we usually say that the model is valid. But not all valid models are &lt;em&gt;good&lt;/em&gt; models. The next section deals with model selection.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;how-to-choose-a-good-linear-model&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;How to choose a good linear model?&lt;/h2&gt;
&lt;p&gt;A model which satisfies the conditions of application is the minimum requirement, but you will likely find several models that meet this criteria. So one may wonder &lt;strong&gt;how to choose between different models&lt;/strong&gt; that are all valid?&lt;/p&gt;
&lt;p&gt;The three most common tools to select a good linear model are according to:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value associated to the model,&lt;/li&gt;
&lt;li&gt;the coefficient of determination &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; and&lt;/li&gt;
&lt;li&gt;the Akaike Information Criterion&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The approaches are detailed in the next sections. Note that the first two are applicable to simple and multiple linear regression, whereas the third is only applicable to multiple linear regression.&lt;/p&gt;
&lt;div id=&#34;p-value-associated-to-the-model&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;&lt;span class=&#34;math inline&#34;&gt;\(P\)&lt;/span&gt;-value associated to the model&lt;/h3&gt;
&lt;p&gt;Before interpreting the estimates of a model, it is a good practice to first check the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value associated to the model. This &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value indicates if the model is &lt;strong&gt;better than a model with only the intercept&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The hypotheses of the test (called F-test) are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0: \beta_1 = \beta_2 = \dots = \beta_p = 0\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1:\)&lt;/span&gt; at least one coefficient &lt;span class=&#34;math inline&#34;&gt;\(\beta \ne 0\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value can be found at the bottom of the &lt;code&gt;summary()&lt;/code&gt; output:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(model2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
## lm(formula = mpg ~ wt + hp + disp, data = dat)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -3.891 -1.640 -0.172  1.061  5.861 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(&amp;gt;|t|)    
## (Intercept) 37.105505   2.110815  17.579  &amp;lt; 2e-16 ***
## wt          -3.800891   1.066191  -3.565  0.00133 ** 
## hp          -0.031157   0.011436  -2.724  0.01097 *  
## disp        -0.000937   0.010350  -0.091  0.92851    
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 
## Residual standard error: 2.639 on 28 degrees of freedom
## Multiple R-squared:  0.8268,	Adjusted R-squared:  0.8083 
## F-statistic: 44.57 on 3 and 28 DF,  p-value: 8.65e-11&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 8.65e-11. The null hypothesis is rejected, so we conclude that our model is better than a model with only the intercept because at least one coefficient &lt;span class=&#34;math inline&#34;&gt;\(\beta\)&lt;/span&gt; is significantly different from 0.&lt;/p&gt;
&lt;p&gt;If this &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &amp;gt; 0.05 for one of your model, it means that none of the variables you selected help in explaining the dependent variable. In other words, you should completely forget about this model because it cannot do better than simply taking the mean of the dependent variable.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;coefficient-of-determination-r2&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Coefficient of determination &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;The coefficient of determination, &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt;, is a measure of the &lt;strong&gt;goodness of fit of the model&lt;/strong&gt;. It measures the proportion of the total variability that is explained by the model, or how well the model fits the data.&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; varies between 0 and 1:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(R^2 = 0\)&lt;/span&gt;: the model explains nothing&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(R^2 = 1\)&lt;/span&gt;: the model explains everything&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(0 &amp;lt; R^2 &amp;lt; 1\)&lt;/span&gt;: the model explains part of the variability&lt;/li&gt;
&lt;li&gt;the higher the &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt;, the better the model explains the dependent variable. As a rule of thumb, a &lt;span class=&#34;math inline&#34;&gt;\(R^2 &amp;gt; 0.7\)&lt;/span&gt; indicates a good fit of the model&lt;a href=&#34;#fn16&#34; class=&#34;footnote-ref&#34; id=&#34;fnref16&#34;&gt;&lt;sup&gt;16&lt;/sup&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that in a simple linear regression model, the coefficient of determination is equal to the square of the Pearson &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;correlation coefficient&lt;/a&gt;:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[R^2 = corr(X, Y)^2\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Applied on our &lt;code&gt;model2&lt;/code&gt; with miles/gallon as dependent variable, and weight, horsepower and displacement as independent variables, we have:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(model2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
## lm(formula = mpg ~ wt + hp + disp, data = dat)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -3.891 -1.640 -0.172  1.061  5.861 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(&amp;gt;|t|)    
## (Intercept) 37.105505   2.110815  17.579  &amp;lt; 2e-16 ***
## wt          -3.800891   1.066191  -3.565  0.00133 ** 
## hp          -0.031157   0.011436  -2.724  0.01097 *  
## disp        -0.000937   0.010350  -0.091  0.92851    
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 
## Residual standard error: 2.639 on 28 degrees of freedom
## Multiple R-squared:  0.8268,	Adjusted R-squared:  0.8083 
## F-statistic: 44.57 on 3 and 28 DF,  p-value: 8.65e-11&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; is displayed at the bottom of the &lt;code&gt;summary()&lt;/code&gt; output or can be extracted with &lt;code&gt;summary(model2)$r.squared&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; for this model is 0.8268, which means that 82.68% of the variability of the distance traveled with a gallon is explained by the weight, horsepower and displacement of the car. The relatively high &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; means that the weight, horsepower and displacement of a car are good characteristics to explain the distance it can drive with a gallon of fuel.&lt;/p&gt;
&lt;p&gt;Note that if you want to compare models with different number of independent variables, it is best to refer to the adjusted &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; (= 0.8083 here).&lt;/p&gt;
&lt;p&gt;Indeed, adding variables to the model cannot make the &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; to decrease, even if the variables are not related to the dependent variables (so the &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; will artificially increase when adding variables to the model, or at least stay constant). Therefore, the adjusted &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; takes into account the complexity of the model (the number of variables) by penalizing for additional variables, so it is a compromise between goodness of fit and parsimony.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;parsimony&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Parsimony&lt;/h3&gt;
&lt;p&gt;A &lt;strong&gt;parsimonious model (few variables) is usually preferred&lt;/strong&gt; over a complex model (many variables). There are two ways to obtain a parsimonious model from a model with many independent variables:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;We can &lt;strong&gt;iteratively remove the independent variable least significantly related to the dependent variable&lt;/strong&gt; (i.e., the one with the highest &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value in an &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#overall-effect-of-categorical-variables&#34;&gt;analysis of variance table&lt;/a&gt;) until all of them are significantly associated to the response variable, or&lt;/li&gt;
&lt;li&gt;We can select the model based on the &lt;strong&gt;Akaike Information Criterion (AIC)&lt;/strong&gt;. AIC expresses a desire to fit the model with the smallest number of coefficients possible and allows to compare models. According to this criterion, the best model is the one with the lowest AIC. This criterion is based on a compromise between the quality of the fit and its complexity. We usually start from a global model with many independent variables, and the procedure (referred as stepwise algorithm)&lt;a href=&#34;#fn17&#34; class=&#34;footnote-ref&#34; id=&#34;fnref17&#34;&gt;&lt;sup&gt;17&lt;/sup&gt;&lt;/a&gt; automatically compares models then selects the best one according to the AIC.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;We show how to do the second option in R. For the illustration, we start with a model with all variables in the dataset as independent variables (do not forget to transform the factor variables first):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## vs has already been transformed into factor
## so only am is transformed here

## Recoding dat$vs
library(forcats)
dat$am &amp;lt;- as.character(dat$am)
dat$am &amp;lt;- fct_recode(dat$am,
  &amp;quot;Automatic&amp;quot; = &amp;quot;0&amp;quot;,
  &amp;quot;Manual&amp;quot; = &amp;quot;1&amp;quot;
)

model4 &amp;lt;- lm(mpg ~ .,
  data = dat
)

model4 &amp;lt;- step(model4, trace = FALSE)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;(&lt;em&gt;Tip:&lt;/em&gt; The formula &lt;code&gt;mpg ~ .&lt;/code&gt; is a shortcut to consider all variables present in the dataset as independent variables, except the one that has been specified as the dependent variable (&lt;code&gt;mpg&lt;/code&gt; here)).&lt;/p&gt;
&lt;p&gt;The model that has been selected according to this criterion is the following:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(model4)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
## lm(formula = mpg ~ wt + qsec + am, data = dat)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -3.4811 -1.5555 -0.7257  1.4110  4.6610 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(&amp;gt;|t|)    
## (Intercept)   9.6178     6.9596   1.382 0.177915    
## wt           -3.9165     0.7112  -5.507 6.95e-06 ***
## qsec          1.2259     0.2887   4.247 0.000216 ***
## amManual      2.9358     1.4109   2.081 0.046716 *  
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 
## Residual standard error: 2.459 on 28 degrees of freedom
## Multiple R-squared:  0.8497,	Adjusted R-squared:  0.8336 
## F-statistic: 52.75 on 3 and 28 DF,  p-value: 1.21e-11&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Be careful when using an automatic procedure because, even though it is the best model that is selected, it is based:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;on a single criterion (AIC in this case), but more importantly;&lt;/li&gt;
&lt;li&gt;it is based on some set of mathematical rules, which means that industry knowledge or human expertise is not taken into consideration.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I believe that this kind of automatic procedure for model’s selection is a good starting point, but I also believe that the final model should always be checked and tested against other models to make sure it makes sense in practice (apply common sense).&lt;/p&gt;
&lt;p&gt;Last but not least, do not forget to also verify the &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#conditions-of-application-1&#34;&gt;conditions of application&lt;/a&gt; because the stepwise procedure does not guarantee that they are respected.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;visualizations-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Visualizations&lt;/h2&gt;
&lt;p&gt;There are many ways to visualize results of a linear regression. The easiest ones I am aware of are:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;code&gt;visreg()&lt;/code&gt; illustrates the relationships between the dependent and independent variables in different plots (one for each independent variable unless you specify which relationship you want to illustrate):&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(visreg)

visreg(model4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-21-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-21-2.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-21-3.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;ol start=&#34;2&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;code&gt;ggcoefstats()&lt;/code&gt; illustrates the results in one single plot, with many statistical details:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggstatsplot)

ggcoefstats(model4)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-22-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In this plot:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;when the solid line does not cross the vertical dashed line, the estimates is significantly different from 0 at the 5% significance level (i.e., &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &amp;lt; 0.05)&lt;/li&gt;
&lt;li&gt;furthermore, a point to the right (left) of the vertical dashed line means that there is a positive (negative) relationship between the two variables&lt;/li&gt;
&lt;li&gt;the more extreme the point, the stronger the relationship&lt;/li&gt;
&lt;/ul&gt;
&lt;ol start=&#34;3&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;code&gt;plot_summs()&lt;/code&gt; which also illustrates the results but in a more concise way:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(jtools)
library(ggstance)

plot_summs(model4,
  omit.coefs = NULL
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-23-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The advantage of this approach is that it is possible to compare coefficients of multiple models simultaneously (particularly interesting when the models are nested):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;model4bis &amp;lt;- lm(mpg ~ wt + qsec + am + hp,
  data = dat
)

plot_summs(model4,
  model4bis,
  omit.coefs = NULL
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-24-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;to-go-further&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;To go further&lt;/h2&gt;
&lt;p&gt;Below some more advanced topics related to linear regression. Feel free to comment at the end of the article if you believe I missed an important one.&lt;/p&gt;
&lt;div id=&#34;print-models-parameters&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Print model’s parameters&lt;/h3&gt;
&lt;p&gt;Thanks to the &lt;code&gt;model_parameters()&lt;/code&gt; function from the &lt;code&gt;{parameters}&lt;/code&gt; package, you can print a summary of the model in a nicely formatted way to make the output more readable:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(parameters)

model_parameters(model4, summary = TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Parameter   | Coefficient |   SE |         95% CI | t(28) |      p
## ------------------------------------------------------------------
## (Intercept) |        9.62 | 6.96 | [-4.64, 23.87] |  1.38 | 0.178 
## wt          |       -3.92 | 0.71 | [-5.37, -2.46] | -5.51 | &amp;lt; .001
## qsec        |        1.23 | 0.29 | [ 0.63,  1.82] |  4.25 | &amp;lt; .001
## am [Manual] |        2.94 | 1.41 | [ 0.05,  5.83] |  2.08 | 0.047&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And if you are using &lt;a href=&#34;https://statsandr.com/blog/getting-started-in-r-markdown/&#34;&gt;R Markdown&lt;/a&gt;, you can use the &lt;code&gt;print_html()&lt;/code&gt; function to get a compact and yet comprehensive summary table in your HTML file:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(gt)

print_html(model_parameters(model4, summary = TRUE))&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;yywrdylzvd&#34; style=&#34;padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;&#34;&gt;
&lt;style&gt;#yywrdylzvd table {
  font-family: system-ui, &#39;Segoe UI&#39;, Roboto, Helvetica, Arial, sans-serif, &#39;Apple Color Emoji&#39;, &#39;Segoe UI Emoji&#39;, &#39;Segoe UI Symbol&#39;, &#39;Noto Color Emoji&#39;;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

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

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

#yywrdylzvd .gt_table {
  display: table;
  border-collapse: collapse;
  line-height: normal;
  margin-left: auto;
  margin-right: auto;
  color: #333333;
  font-size: 100%;
  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;
}

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

#yywrdylzvd .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;
}

#yywrdylzvd .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;
}

#yywrdylzvd .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;
}

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

#yywrdylzvd .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;
}

#yywrdylzvd .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;
}

#yywrdylzvd .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;
}

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

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

#yywrdylzvd .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%;
}

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

#yywrdylzvd .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;
}

#yywrdylzvd .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;
}

#yywrdylzvd .gt_from_md &gt; :first-child {
  margin-top: 0;
}

#yywrdylzvd .gt_from_md &gt; :last-child {
  margin-bottom: 0;
}

#yywrdylzvd .gt_row {
  padding-top: 4px;
  padding-bottom: 4px;
  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;
}

#yywrdylzvd .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;
}

#yywrdylzvd .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;
}

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

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

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

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

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

#yywrdylzvd .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;
}

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

#yywrdylzvd .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;
}

#yywrdylzvd .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;
}

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

#yywrdylzvd .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;
}

#yywrdylzvd .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;
}

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

#yywrdylzvd .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;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#yywrdylzvd div.Reactable &gt; div.rt-table &gt; div.rt-thead &gt; div.rt-tr.rt-tr-group-header &gt; div.rt-th-group:after {
  height: 0px !important;
}
&lt;/style&gt;
&lt;table class=&#34;gt_table&#34; data-quarto-disable-processing=&#34;false&#34; data-quarto-bootstrap=&#34;false&#34;&gt;
  &lt;thead&gt;
    &lt;tr class=&#34;gt_col_headings&#34;&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_left&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;Parameter&#34;&gt;Parameter&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_center&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;Coefficient&#34;&gt;Coefficient&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_center&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;SE&#34;&gt;SE&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_center&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;a95%-CI&#34;&gt;95% CI&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_center&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;t(28)&#34;&gt;t(28)&lt;/th&gt;
      &lt;th class=&#34;gt_col_heading gt_columns_bottom_border gt_center&#34; rowspan=&#34;1&#34; colspan=&#34;1&#34; scope=&#34;col&#34; id=&#34;p&#34;&gt;p&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody class=&#34;gt_table_body&#34;&gt;
    &lt;tr&gt;&lt;td headers=&#34;Parameter&#34; class=&#34;gt_row gt_left&#34; style=&#34;border-right-width: 1px; border-right-style: solid; border-right-color: #d3d3d3;&#34;&gt;(Intercept)&lt;/td&gt;
&lt;td headers=&#34;Coefficient&#34; class=&#34;gt_row gt_center&#34;&gt;9.62&lt;/td&gt;
&lt;td headers=&#34;SE&#34; class=&#34;gt_row gt_center&#34;&gt;6.96&lt;/td&gt;
&lt;td headers=&#34;95% CI&#34; class=&#34;gt_row gt_center&#34;&gt;(-4.64, 23.87)&lt;/td&gt;
&lt;td headers=&#34;t(28)&#34; class=&#34;gt_row gt_center&#34;&gt;1.38&lt;/td&gt;
&lt;td headers=&#34;p&#34; class=&#34;gt_row gt_center&#34;&gt;0.178 &lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Parameter&#34; class=&#34;gt_row gt_left&#34; style=&#34;border-right-width: 1px; border-right-style: solid; border-right-color: #d3d3d3;&#34;&gt;wt&lt;/td&gt;
&lt;td headers=&#34;Coefficient&#34; class=&#34;gt_row gt_center&#34;&gt;-3.92&lt;/td&gt;
&lt;td headers=&#34;SE&#34; class=&#34;gt_row gt_center&#34;&gt;0.71&lt;/td&gt;
&lt;td headers=&#34;95% CI&#34; class=&#34;gt_row gt_center&#34;&gt;(-5.37, -2.46)&lt;/td&gt;
&lt;td headers=&#34;t(28)&#34; class=&#34;gt_row gt_center&#34;&gt;-5.51&lt;/td&gt;
&lt;td headers=&#34;p&#34; class=&#34;gt_row gt_center&#34;&gt;&amp;lt; .001&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Parameter&#34; class=&#34;gt_row gt_left&#34; style=&#34;border-right-width: 1px; border-right-style: solid; border-right-color: #d3d3d3;&#34;&gt;qsec&lt;/td&gt;
&lt;td headers=&#34;Coefficient&#34; class=&#34;gt_row gt_center&#34;&gt;1.23&lt;/td&gt;
&lt;td headers=&#34;SE&#34; class=&#34;gt_row gt_center&#34;&gt;0.29&lt;/td&gt;
&lt;td headers=&#34;95% CI&#34; class=&#34;gt_row gt_center&#34;&gt;(0.63, 1.82)&lt;/td&gt;
&lt;td headers=&#34;t(28)&#34; class=&#34;gt_row gt_center&#34;&gt;4.25&lt;/td&gt;
&lt;td headers=&#34;p&#34; class=&#34;gt_row gt_center&#34;&gt;&amp;lt; .001&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td headers=&#34;Parameter&#34; class=&#34;gt_row gt_left&#34; style=&#34;border-right-width: 1px; border-right-style: solid; border-right-color: #d3d3d3;&#34;&gt;am (Manual)&lt;/td&gt;
&lt;td headers=&#34;Coefficient&#34; class=&#34;gt_row gt_center&#34;&gt;2.94&lt;/td&gt;
&lt;td headers=&#34;SE&#34; class=&#34;gt_row gt_center&#34;&gt;1.41&lt;/td&gt;
&lt;td headers=&#34;95% CI&#34; class=&#34;gt_row gt_center&#34;&gt;(0.05, 5.83)&lt;/td&gt;
&lt;td headers=&#34;t(28)&#34; class=&#34;gt_row gt_center&#34;&gt;2.08&lt;/td&gt;
&lt;td headers=&#34;p&#34; class=&#34;gt_row gt_center&#34;&gt;0.047 &lt;/td&gt;&lt;/tr&gt;
  &lt;/tbody&gt;
  
&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;automatic-reporting&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Automatic reporting&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;report()&lt;/code&gt; function from the package of the same name allows to automatically produces reports of models according to best practices guidelines:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(report)

report(model4)[1]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;We fitted a linear model (estimated using OLS) to predict mpg with wt, qsec and am (formula: mpg ~ wt + qsec + am). The model explains a statistically significant and substantial proportion of variance (R2 = 0.85, F(3, 28) = 52.75, p &amp;lt; .001, adj. R2 = 0.83). The model&amp;#39;s intercept, corresponding to wt = 0, qsec = 0 and am = Automatic, is at 9.62 (95% CI [-4.64, 23.87], t(28) = 1.38, p = 0.178). Within this model:\n\n  - The effect of wt is statistically significant and negative (beta = -3.92, 95% CI [-5.37, -2.46], t(28) = -5.51, p &amp;lt; .001; Std. beta = -0.64, 95% CI [-0.87, -0.40])\n  - The effect of qsec is statistically significant and positive (beta = 1.23, 95% CI [0.63, 1.82], t(28) = 4.25, p &amp;lt; .001; Std. beta = 0.36, 95% CI [0.19, 0.54])\n  - The effect of am [Manual] is statistically significant and positive (beta = 2.94, 95% CI [0.05, 5.83], t(28) = 2.08, p = 0.047; Std. beta = 0.49, 95% CI [7.59e-03, 0.97])\n\nStandardized parameters were obtained by fitting the model on a standardized version of the dataset. 95% Confidence Intervals (CIs) and p-values were computed using a Wald t-distribution approximation.&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the function also works for dataframes, &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt; and other models.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;predictions&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Predictions&lt;/h3&gt;
&lt;p&gt;Linear regression is also very often used for &lt;strong&gt;predictive purposes&lt;/strong&gt;. Confidence and prediction intervals for &lt;strong&gt;new data&lt;/strong&gt; can be computed with the &lt;code&gt;predict()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;Suppose we want to predict the miles/gallon for a car with a manual transmission, weighting 3000 lbs and which drives a quarter of a mile (&lt;code&gt;qsec&lt;/code&gt;) in 18 seconds:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# confidence interval for new data
predict(model4,
  new = data.frame(wt = 3, qsec = 18, am = &amp;quot;Manual&amp;quot;),
  interval = &amp;quot;confidence&amp;quot;,
  level = .95
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##        fit      lwr    upr
## 1 22.87005 21.09811 24.642&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# prediction interval for new data
predict(model4,
  new = data.frame(wt = 3, qsec = 18, am = &amp;quot;Manual&amp;quot;),
  interval = &amp;quot;prediction&amp;quot;,
  level = .95
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##        fit      lwr      upr
## 1 22.87005 17.53074 28.20937&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Based on our model, it is expected that this car will drive 22.87 miles with a gallon.&lt;/p&gt;
&lt;p&gt;The difference between the confidence and prediction interval is that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a &lt;strong&gt;confidence&lt;/strong&gt; interval gives the predicted value for the &lt;strong&gt;mean&lt;/strong&gt; of &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; for a new observation, whereas&lt;/li&gt;
&lt;li&gt;a &lt;strong&gt;prediction&lt;/strong&gt; interval gives the predicted value for an &lt;strong&gt;individual&lt;/strong&gt; &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt; for a new observation.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The prediction interval is wider than the confidence interval to account for the &lt;strong&gt;additional uncertainty due to predicting an individual response&lt;/strong&gt;, and not the mean, for a given value of &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;linear-hypothesis-tests&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Linear hypothesis tests&lt;/h3&gt;
&lt;p&gt;Linear hypothesis tests make it possible to generalize the F-test mentioned in this &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#p-value-associated-to-the-model&#34;&gt;section&lt;/a&gt;, while offering the possibility to perform either tests of comparison of coefficients, or tests of equality of linear combinations of coefficients.&lt;/p&gt;
&lt;p&gt;For example, to test the linear constraint:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0: \beta_1 = \beta_2 = 0\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1:\)&lt;/span&gt; not &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;we use the &lt;code&gt;linearHypothesis()&lt;/code&gt; function of the &lt;code&gt;{car}&lt;/code&gt; package as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(car)
linearHypothesis(model4, c(&amp;quot;wt = 0&amp;quot;, &amp;quot;qsec = 0&amp;quot;))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Linear hypothesis test:
## wt = 0
## qsec = 0
## 
## Model 1: restricted model
## Model 2: mpg ~ wt + qsec + am
## 
##   Res.Df    RSS Df Sum of Sq      F   Pr(&amp;gt;F)    
## 1     30 720.90                                 
## 2     28 169.29  2    551.61 45.618 1.55e-09 ***
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We reject the null hypothesis and we conclude that at least one of &lt;span class=&#34;math inline&#34;&gt;\(\beta_1\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\beta_2\)&lt;/span&gt; is different from 0 (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 1.55e-09).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;overall-effect-of-categorical-variables&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Overall effect of categorical variables&lt;/h3&gt;
&lt;p&gt;When the independent variables are categorical with &lt;span class=&#34;math inline&#34;&gt;\(k\)&lt;/span&gt; categories, the regression table provides &lt;span class=&#34;math inline&#34;&gt;\(k-1\)&lt;/span&gt; &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;model5 &amp;lt;- lm(mpg ~ vs + am + as.factor(cyl),
  data = dat
)

summary(model5)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
## lm(formula = mpg ~ vs + am + as.factor(cyl), data = dat)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -6.2821 -1.4402  0.0391  1.8845  6.2179 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(&amp;gt;|t|)    
## (Intercept)       22.809      2.928   7.789 2.24e-08 ***
## vsStraight         1.708      2.235   0.764  0.45135    
## amManual           3.165      1.528   2.071  0.04805 *  
## as.factor(cyl)6   -5.399      1.837  -2.938  0.00668 ** 
## as.factor(cyl)8   -8.161      2.892  -2.822  0.00884 ** 
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 
## Residual standard error: 3.097 on 27 degrees of freedom
## Multiple R-squared:  0.7701,	Adjusted R-squared:  0.736 
## F-statistic: 22.61 on 4 and 27 DF,  p-value: 2.741e-08&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The variables &lt;code&gt;vs&lt;/code&gt; and &lt;code&gt;am&lt;/code&gt; have 2 levels so one is displayed in the regression output. The variable &lt;code&gt;cyl&lt;/code&gt; has 3 levels (4, 6 and 8) so 2 of them are displayed. The overall effect of &lt;code&gt;vs&lt;/code&gt; and &lt;code&gt;am&lt;/code&gt; are reported in the &lt;code&gt;Pr(&amp;gt;|t|)&lt;/code&gt; column, but not the &lt;strong&gt;overall&lt;/strong&gt; effect of &lt;code&gt;cyl&lt;/code&gt; because there are more than 2 levels for this variable.&lt;/p&gt;
&lt;p&gt;To get the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value of the overall effect of a categorical variable, we need to get an analysis of variance table via the &lt;code&gt;Anova()&lt;/code&gt; function from the &lt;code&gt;{car}&lt;/code&gt; package:&lt;a href=&#34;#fn18&#34; class=&#34;footnote-ref&#34; id=&#34;fnref18&#34;&gt;&lt;sup&gt;18&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(car)
Anova(model5)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Anova Table (Type II tests)
## 
## Response: mpg
##                 Sum Sq Df F value  Pr(&amp;gt;F)  
## vs               5.601  1  0.5841 0.45135  
## am              41.122  1  4.2886 0.04805 *
## as.factor(cyl)  94.591  2  4.9324 0.01493 *
## Residuals      258.895 27                  
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From this analysis of variance table, we conclude that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;vs&lt;/code&gt; is not significantly associated with &lt;code&gt;mpg&lt;/code&gt; (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.451)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;am&lt;/code&gt; and &lt;code&gt;cyl&lt;/code&gt; are significantly associated with &lt;code&gt;mpg&lt;/code&gt; (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values &amp;lt; 0.05)&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;interaction&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Interaction&lt;/h3&gt;
&lt;p&gt;So far we have covered multiple linear regression without any interaction.&lt;/p&gt;
&lt;p&gt;There is an &lt;strong&gt;interaction&lt;/strong&gt; effect between factors A and B &lt;strong&gt;if the effect of factor A on the response depends on the level taken by factor B&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In R, interaction can be added as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;model6 &amp;lt;- lm(mpg ~ wt + am + wt:am,
  data = dat
)

# Or in a shorter way:
model6 &amp;lt;- lm(mpg ~ wt * am,
  data = dat
)

summary(model6)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
## lm(formula = mpg ~ wt * am, data = dat)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -3.6004 -1.5446 -0.5325  0.9012  6.0909 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(&amp;gt;|t|)    
## (Intercept)  31.4161     3.0201  10.402 4.00e-11 ***
## wt           -3.7859     0.7856  -4.819 4.55e-05 ***
## amManual     14.8784     4.2640   3.489  0.00162 ** 
## wt:amManual  -5.2984     1.4447  -3.667  0.00102 ** 
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 
## Residual standard error: 2.591 on 28 degrees of freedom
## Multiple R-squared:  0.833,	Adjusted R-squared:  0.8151 
## F-statistic: 46.57 on 3 and 28 DF,  p-value: 5.209e-11&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From the output we conclude that there is an interaction between the weight and the transmission (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.00102). This means that the effect of the weight on the distance traveled with a gallon &lt;strong&gt;depends on the transmission type&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The easiest way to handle interaction is to visualize the relationship for each level of the categorical variable:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visreg(model6, &amp;quot;wt&amp;quot;, by = &amp;quot;am&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/index_files/figure-html/unnamed-chunk-33-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;We see that the relationship between weight and miles/gallon is stronger (the slope is steeper) for cars with a manual transmission compared to cars with an automatic transmission.&lt;/p&gt;
&lt;p&gt;This is a good example to illustrate the point that when studying a relationship between two variables, say &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt;, if one also has data for other variables which are potentially associated with both &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(Y\)&lt;/span&gt;, it is important to include them in the regression and to analyze the relationship &lt;strong&gt;conditionally on these variables&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Omitting some variables that should be included in the model may lead to erroneous and misleading conclusions, up to the point that the relationship is completely reversed (a phenomenon referred as &lt;a href=&#34;https://en.wikipedia.org/wiki/Simpson%27s_paradox&#34; target=&#34;_blank&#34;&gt;Simpson’s paradox&lt;/a&gt;).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;summary&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;In this article, we started with a reminder of &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#simple-linear-regression-reminder&#34;&gt;simple linear regression&lt;/a&gt; and in particular its &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#principle&#34;&gt;principle&lt;/a&gt; and how to &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#interpretations-of-coefficients-widehatbeta&#34;&gt;interpret the results&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;This laid the foundations for a better understanding of &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#multiple-linear-regression&#34;&gt;multiple linear regression&lt;/a&gt;. After explaining its &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#principle-1&#34;&gt;principle&lt;/a&gt;, we showed how to &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#interpretations-of-coefficients-widehatbeta-1&#34;&gt;interpret the output&lt;/a&gt; and how to choose a &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#how-to-choose-a-good-linear-model&#34;&gt;good linear model&lt;/a&gt;. We then mentioned a couple of &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#visualizations-1&#34;&gt;visualizations&lt;/a&gt; and finished the article with some more &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#to-go-further&#34;&gt;advanced topics&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to understand better linear regression and gave you the confidence to do your own linear regressions in R. If you need to model a binary variable instead of a quantitative continuous variable, see how to perform a &lt;a href=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/&#34;&gt;binary logistic regression in R&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-austin2015number&#34; class=&#34;csl-entry&#34;&gt;
Austin, Peter C, and Ewout W Steyerberg. 2015. &lt;span&gt;“The Number of Subjects Per Variable Required in Linear Regression Analyses.”&lt;/span&gt; &lt;em&gt;Journal of Clinical Epidemiology&lt;/em&gt; 68 (6): 627–36.
&lt;/div&gt;
&lt;div id=&#34;ref-ernst2017regression&#34; class=&#34;csl-entry&#34;&gt;
Ernst, Anja F, and Casper J Albers. 2017. &lt;span&gt;“Regression Assumptions in Clinical Psychology Research Practice?a Systematic Review of Common Misconceptions.”&lt;/span&gt; &lt;em&gt;PeerJ&lt;/em&gt; 5: e3323.
&lt;/div&gt;
&lt;div id=&#34;ref-james2013introduction&#34; class=&#34;csl-entry&#34;&gt;
James, Gareth, Daniela Witten, Trevor Hastie, and Robert Tibshirani. 2013. &lt;em&gt;An Introduction to Statistical Learning&lt;/em&gt;. Vol. 112. Springer.
&lt;/div&gt;
&lt;div id=&#34;ref-lumley2002importance&#34; class=&#34;csl-entry&#34;&gt;
Lumley, Thomas, Paula Diehr, Scott Emerson, and Lu Chen. 2002. &lt;span&gt;“The Importance of the Normality Assumption in Large Public Health Data Sets.”&lt;/span&gt; &lt;em&gt;Annual Review of Public Health&lt;/em&gt; 23 (1): 151–69.
&lt;/div&gt;
&lt;div id=&#34;ref-schmidt2018linear&#34; class=&#34;csl-entry&#34;&gt;
Schmidt, Amand F, and Chris Finan. 2018. &lt;span&gt;“Linear Regression and the Normality Assumption.”&lt;/span&gt; &lt;em&gt;Journal of Clinical Epidemiology&lt;/em&gt; 98: 146–51.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;Some people see regression analysis as a part of inferential statistics. It is true, as a sample is taken to evaluate the link between two or more variables in a population of interest. I tend to distinguish regression from inferential statistics for the simple reasons that (i) regressions are often used to a broader extent (for predictive analyses, among others), and because (ii) the main goal of linear regression (see this &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#simple-linear-regression-reminder&#34;&gt;section&lt;/a&gt;) differs from the objectives of confidence intervals and hypothesis testing well known in the field of inferential statistics.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Formally, ANOVA can also be used to compare 2 groups, but in practice we tend to use it for 3 or more groups, leaving the t-test for 2 groups.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;More information about the dataset can be found by executing &lt;code&gt;?mtcars&lt;/code&gt;.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;Note that it best to avoid interpreting the intercept when &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; cannot be equal to 0 or when it makes no sense in practice.&lt;a href=&#34;#fnref4&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn5&#34;&gt;&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is the number of observations.&lt;a href=&#34;#fnref5&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn6&#34;&gt;&lt;p&gt;Other values than 0 are accepted as well. In that case, the test statistic becomes &lt;span class=&#34;math inline&#34;&gt;\(T_{n - 2} = \frac{\widehat\beta - a}{se(\widehat\beta_1)}\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(a\)&lt;/span&gt; is the hypothesized slope.&lt;a href=&#34;#fnref6&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn7&#34;&gt;&lt;p&gt;Note that linearity can be checked with a scatterplot of the two variables, or via a scatterplot of the residuals and the fitted values. See more about this in this &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/#conditions-of-application-1&#34;&gt;section&lt;/a&gt;.&lt;a href=&#34;#fnref7&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn8&#34;&gt;&lt;p&gt;An observation is considered as an outlier based on the Cook’s distance if its value is &amp;gt; 1.&lt;a href=&#34;#fnref8&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn9&#34;&gt;&lt;p&gt;An observation has a high leverage value (and thus needs to be investigated) if it is greater than &lt;span class=&#34;math inline&#34;&gt;\(2p/n\)&lt;/span&gt;, where &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt; is the number of parameters in the model (intercept included) and &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is the number of observations.&lt;a href=&#34;#fnref9&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn10&#34;&gt;&lt;p&gt;You can always change the reference level with the &lt;code&gt;relevel()&lt;/code&gt; function. See more &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/&#34;&gt;data manipulation techniques&lt;/a&gt;.&lt;a href=&#34;#fnref10&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn11&#34;&gt;&lt;p&gt;Note that linearity can also be tested with a scatterplot of the residuals and the fitted values.&lt;a href=&#34;#fnref11&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn12&#34;&gt;&lt;p&gt;After installing the &lt;code&gt;{performance}&lt;/code&gt; package, you will also need to install the &lt;code&gt;{see}&lt;/code&gt; package manually. See &lt;a href=&#34;https://statsandr.com/blog/an-efficient-way-to-install-and-load-r-packages/&#34;&gt;how to install a R package&lt;/a&gt; if you need more help.&lt;a href=&#34;#fnref12&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn13&#34;&gt;&lt;p&gt;I use the threshold of 10 because, as shown by &lt;span class=&#34;citation&#34;&gt;James et al. (&lt;a href=&#34;#ref-james2013introduction&#34;&gt;2013&lt;/a&gt;)&lt;/span&gt;, a value between 5 and 10 indicates a moderate correlation, while VIF values greater than 10 indicate a high and &lt;em&gt;non-tolerable&lt;/em&gt; correlation.&lt;a href=&#34;#fnref13&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn14&#34;&gt;&lt;p&gt;&lt;span class=&#34;citation&#34;&gt;Austin and Steyerberg (&lt;a href=&#34;#ref-austin2015number&#34;&gt;2015&lt;/a&gt;)&lt;/span&gt; showed that two subjects per variable tends to permit accurate estimation of regression coefficients in a linear regression model estimated using ordinary least squares. Moreover, the general rule of thumb says that there should be at least 10 observations per variable &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-schmidt2018linear&#34;&gt;Schmidt and Finan 2018&lt;/a&gt;)&lt;/span&gt;. Our dataset contains 32 observations, above the minimum of 10 subjects per variable.&lt;a href=&#34;#fnref14&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn15&#34;&gt;&lt;p&gt;If you apply a logarithmic transformation, see two guides on how to interpret the results: in &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/images/Interpret-Regression-Coefficient-Estimates-in-linear-regression.png&#34;&gt;English&lt;/a&gt; and in &lt;a href=&#34;https://www.parisschoolofeconomics.eu/docs/yin-remi/interpretation-des-coefficients.pdf&#34; target=&#34;_blank&#34;&gt;French&lt;/a&gt;.&lt;a href=&#34;#fnref15&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn16&#34;&gt;&lt;p&gt;Note that a high &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; does not guarantee that you selected the best variables or that your model is good. It simply tells that the model fits the data quite well. It is advised to apply common sense when comparing models and not only refer to &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; (in particular when &lt;span class=&#34;math inline&#34;&gt;\(R^2\)&lt;/span&gt; are close).&lt;a href=&#34;#fnref16&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn17&#34;&gt;&lt;p&gt;There are two main methods; backward and forward. The backward method consists in starting from the model containing all the explanatory variables likely to be relevant, then recursively removing the variable which reduces the information criterion of the model, until no reduction is possible. The forward method is the reverse of the backward method in the sense that we start from a one-variable model with the lowest information criterion and at each step, an explanatory variable is added. By default, the &lt;code&gt;step()&lt;/code&gt; function in R combines the backward and forward methods.&lt;a href=&#34;#fnref17&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn18&#34;&gt;&lt;p&gt;To not be confused with the &lt;code&gt;anova()&lt;/code&gt; function because it provides results that depend on the order in which the variables appear in the model.&lt;a href=&#34;#fnref18&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Hypothesis test by hand</title>
      <link>https://statsandr.com/blog/hypothesis-test-by-hand/</link>
      <pubDate>Wed, 27 Jan 2021 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/hypothesis-test-by-hand/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#descriptive-versus-inferential-statistics&#34; id=&#34;toc-descriptive-versus-inferential-statistics&#34;&gt;Descriptive versus inferential statistics&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#motivations-and-limitations&#34; id=&#34;toc-motivations-and-limitations&#34;&gt;Motivations and limitations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#hypothesis-test&#34; id=&#34;toc-hypothesis-test&#34;&gt;Hypothesis test&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#why&#34; id=&#34;toc-why&#34;&gt;Why?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#when&#34; id=&#34;toc-when&#34;&gt;When?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#how&#34; id=&#34;toc-how&#34;&gt;How?&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#method-a-comparing-the-test-statistic-with-the-critical-value&#34; id=&#34;toc-method-a-comparing-the-test-statistic-with-the-critical-value&#34;&gt;Method A: Comparing the test statistic with the critical value&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#step-1-stating-the-null-and-alternative-hypothesis&#34; id=&#34;toc-step-1-stating-the-null-and-alternative-hypothesis&#34;&gt;Step #1: Stating the null and alternative hypothesis&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#step-2-computing-the-test-statistic&#34; id=&#34;toc-step-2-computing-the-test-statistic&#34;&gt;Step #2: Computing the test statistic&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#step-3-finding-the-critical-value&#34; id=&#34;toc-step-3-finding-the-critical-value&#34;&gt;Step #3: Finding the critical value&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#step-4-concluding-and-interpreting-the-results&#34; id=&#34;toc-step-4-concluding-and-interpreting-the-results&#34;&gt;Step #4: Concluding and interpreting the results&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#why-dont-we-accept-h_0&#34; id=&#34;toc-why-dont-we-accept-h_0&#34;&gt;Why don’t we accept &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#method-b-comparing-the-p-value-with-the-significance-level-alpha&#34; id=&#34;toc-method-b-comparing-the-p-value-with-the-significance-level-alpha&#34;&gt;Method B: Comparing the &lt;em&gt;p&lt;/em&gt;-value with the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#step-1-stating-the-null-and-alternative-hypothesis-1&#34; id=&#34;toc-step-1-stating-the-null-and-alternative-hypothesis-1&#34;&gt;Step #1: Stating the null and alternative hypothesis&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#step-2-computing-the-test-statistic-1&#34; id=&#34;toc-step-2-computing-the-test-statistic-1&#34;&gt;Step #2: Computing the test statistic&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#step-3-computing-the-p-value&#34; id=&#34;toc-step-3-computing-the-p-value&#34;&gt;Step #3: Computing the &lt;em&gt;p&lt;/em&gt;-value&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#step-4-concluding-and-interpreting-the-results-1&#34; id=&#34;toc-step-4-concluding-and-interpreting-the-results-1&#34;&gt;Step #4: Concluding and interpreting the results&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#method-c-comparing-the-target-parameter-with-the-confidence-interval&#34; id=&#34;toc-method-c-comparing-the-target-parameter-with-the-confidence-interval&#34;&gt;Method C: Comparing the target parameter with the confidence interval&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#step-1-stating-the-null-and-alternative-hypothesis-2&#34; id=&#34;toc-step-1-stating-the-null-and-alternative-hypothesis-2&#34;&gt;Step #1: Stating the null and alternative hypothesis&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#step-2-computing-the-confidence-interval&#34; id=&#34;toc-step-2-computing-the-confidence-interval&#34;&gt;Step #2: Computing the confidence interval&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#step-3-concluding-and-interpreting-the-results&#34; id=&#34;toc-step-3-concluding-and-interpreting-the-results&#34;&gt;Step #3: Concluding and interpreting the results&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#which-method-to-choose&#34; id=&#34;toc-which-method-to-choose&#34;&gt;Which method to choose?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#summary&#34; id=&#34;toc-summary&#34;&gt;Summary&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2021-01-27-hypothesis-test-by-hand_files/hypothesis-test-by-hand.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;descriptive-versus-inferential-statistics&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Descriptive versus inferential statistics&lt;/h1&gt;
&lt;p&gt;Remember that &lt;strong&gt;&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics&lt;/a&gt;&lt;/strong&gt; is the branch of statistics aiming at &lt;strong&gt;describing and summarizing a set of data&lt;/strong&gt; in the best possible manner, that is, by reducing it down to a few meaningful key measures and visualizations—with as little loss of information as possible. In other words, the branch of &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics&lt;/a&gt; helps to have a better understanding and a clear image about a set of observations thanks to summary statistics and graphics. With descriptive statistics, there is no uncertainty because we describe only the group of observations that we decided to work on and no attempt is made to generalize the observed characteristics to another or to a larger group of observations.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;a href=&#34;https://statsandr.com/tags/inferential-statistics/&#34;&gt;Inferential statistics&lt;/a&gt;&lt;/strong&gt;, one the other hand, is the branch of statistics that uses a random sample of data taken from a population to make inferences, i.e., to &lt;strong&gt;draw conclusions about the &lt;em&gt;population&lt;/em&gt; of interest&lt;/strong&gt; (see the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;difference between population and sample&lt;/a&gt; if you need a refresh of the two concepts). In other words, information from the sample is used to make generalizations about the parameter of interest in the population.&lt;/p&gt;
&lt;p&gt;The two most important tools used in the domain of inferential statistics are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;hypothesis test (which is the main subject of the present article), and&lt;/li&gt;
&lt;li&gt;confidence interval (which is briefly discussed in this &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#method-c-comparing-the-target-parameter-with-the-confidence-interval&#34;&gt;section&lt;/a&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;motivations-and-limitations&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Motivations and limitations&lt;/h1&gt;
&lt;p&gt;Via my &lt;a href=&#34;https://www.antoinesoetewey.com/teaching/&#34; target=&#34;_blank&#34;&gt;teaching&lt;/a&gt; tasks, I realized that many students (especially in introductory statistic classes) struggle to perform hypothesis tests and interpret the results. It seems to me that these students often encounter difficulties mainly because hypothesis testing is rather unclear and abstract to them.&lt;/p&gt;
&lt;p&gt;One of the reason it looks abstract to them is because they do not understand the final goal of hypothesis testing—the “why” behind this tool. They often do inferential statistics without understanding the reasoning behind it, as if they were following a cooking recipe which does not require any thinking. However, as soon as they understand the principle underlying hypothesis testing, it is much easier for them to apply the concepts and solve the exercises.&lt;/p&gt;
&lt;p&gt;For this reason, I though it would be useful to write an article on the goal of hypothesis tests (the “why?”), in which context they should be used (the “when?”), how they work (the “how?”) and how to interpret the results (the “so what?”). Like anything else in statistics, it becomes much easier to apply a concept in practice when we understand what we are testing or what we are trying to demonstrate beforehand.&lt;/p&gt;
&lt;p&gt;In this article, I present—as comprehensibly as possible—the different &lt;strong&gt;steps required to perform and conclude a hypothesis test by hand&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;These steps are illustrated with a basic example. This will build the theoretical foundations of hypothesis testing, which will in turn be of great help for the understanding of most &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Hypothesis tests come in many forms and can be used for many parameters or research questions. The steps I present in this article are not applicable to &lt;em&gt;all&lt;/em&gt; hypothesis test, unfortunately.&lt;/p&gt;
&lt;p&gt;They are however, appropriate for &lt;em&gt;at least&lt;/em&gt; the most common hypothesis tests—the tests on:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;One mean: &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Two means:
&lt;ul&gt;
&lt;li&gt;independent samples: &lt;span class=&#34;math inline&#34;&gt;\(\mu_1\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\mu_2\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;paired samples: &lt;span class=&#34;math inline&#34;&gt;\(\mu_D\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;One proportion: &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Two proportions: &lt;span class=&#34;math inline&#34;&gt;\(p_1\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(p_2\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;One variance: &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Two variances: &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2_1\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2_2\)&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The good news is that the principles behind these 6 statistical tests (and many more) are exactly the same. So if you understand the intuition and the process for one of them, all others pretty much follow.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;hypothesis-test&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Hypothesis test&lt;/h1&gt;
&lt;div id=&#34;why&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Why?&lt;/h2&gt;
&lt;p&gt;Unlike &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt; where we only describe the data at hand, &lt;strong&gt;hypothesis tests use a subset of observations&lt;/strong&gt;, referred as a &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;sample&lt;/a&gt;, &lt;strong&gt;to draw conclusions about a population&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;One may wonder why we would try to “guess” or make inference about a parameter of a population based on a sample, instead of simply collecting data for the entire population, compute statistics we are interested in and take decisions based upon that.&lt;/p&gt;
&lt;p&gt;The main reason we actually use a sample instead of the entire population is because, most of the time, collecting data on the entire population is practically impossible, too complex, too expensive, it would take too long, or a combination of any of these.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;So the &lt;strong&gt;overall objective of a hypothesis test is to draw conclusions in order to confirm or refute a belief about a population&lt;/strong&gt;, based on a smaller group of observations.&lt;/p&gt;
&lt;p&gt;In practice, we take some measurements of the variable of interest—representing the sample(s)—and we check whether our measurements are likely or not given our assumption (our belief). Based on the &lt;a href=&#34;https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/&#34;&gt;probability&lt;/a&gt; of observing the sample(s) we have, we decide whether we can trust our belief or not.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;when&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;When?&lt;/h2&gt;
&lt;p&gt;Hypothesis tests have many practical applications.&lt;/p&gt;
&lt;p&gt;Here are different situations illustrating when the 6 tests mentioned above would be appropriate:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;One mean: suppose that a health professional would like to test whether the mean weight of Belgian adults is different than 80 kg (176.4 lbs).&lt;/li&gt;
&lt;li&gt;Two means:
&lt;ul&gt;
&lt;li&gt;Independent samples: suppose that a physiotherapist would like to test the effectiveness of a new treatment by measuring the mean response time (in seconds) for patients in a control group and patients in a treatment group, where patients in the two groups are different.&lt;/li&gt;
&lt;li&gt;Paired samples: suppose that a physiotherapist would like to test the effectiveness of a new treatment by measuring the mean response time (in seconds) before and after a treatment, where patients are measured twice—before and after treatment, so patients are the same in the 2 samples.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;One proportion: suppose that a political pundit would like to test whether the proportion of citizens who are going to vote for a specific candidate is smaller than 30%.&lt;/li&gt;
&lt;li&gt;Two proportions: suppose that a doctor would like to test whether the proportion of smokers is different between professional and amateur athletes.&lt;/li&gt;
&lt;li&gt;One variance: suppose that an engineer would like to test whether a voltmeter has a lower variability than what is imposed by the safety standards.&lt;/li&gt;
&lt;li&gt;Two variances: suppose that, in a factory, two production lines work independently from each other. The financial manager would like to test whether the costs of the weekly maintenance of these two machines have the same variance. Note that a test on two variances is also often performed to verify the assumption of equal variances, which is required for several other statistical tests, such as the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test&lt;/a&gt; for instance.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Of course, this is a non-exhaustive list of potential applications and many research questions can be answered thanks to a hypothesis test.&lt;/p&gt;
&lt;p&gt;One important point to remember is that in hypothesis testing we are always interested in the population and not in the sample. The sample is used for the aim of drawing conclusions about the population, so we always test in terms of the population.&lt;/p&gt;
&lt;p&gt;Usually, &lt;strong&gt;hypothesis tests are used to answer research questions in confirmatory analyses&lt;/strong&gt;. Confirmatory analyses refer to statistical analyses where hypotheses—deducted from theory—are defined beforehand (preferably before data collection). In this approach, the researcher has a specific idea about the variables under consideration and she is trying to see if her idea, specified as hypotheses, is supported by data.&lt;/p&gt;
&lt;p&gt;On the other hand, hypothesis tests are rarely used in exploratory analyses.&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt; Exploratory analyses aims to uncover possible relationships between the variables under investigation. In this approach, the researcher does not have any clear theory-driven assumptions or ideas in mind before data collection. This is the reason exploratory analyses are sometimes referred as hypothesis-generating analyses—they are used to create some hypotheses, which in turn may be tested via confirmatory analyses at a later stage.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;how&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;How?&lt;/h2&gt;
&lt;p&gt;There are, to my knowledge, 3 different methods to perform a hypothesis tests:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#method-a-comparing-the-test-statistic-with-the-critical-value&#34;&gt;Method A: Comparing the test statistic with the &lt;strong&gt;critical value&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#method-b-comparing-the-p-value-with-the-significance-level-alpha&#34;&gt;Method B: Comparing the &lt;strong&gt;&lt;em&gt;p&lt;/em&gt;-value&lt;/strong&gt; with the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#method-c-comparing-the-target-parameter-with-the-confidence-interval&#34;&gt;Method C: Comparing the target parameter with the &lt;strong&gt;confidence interval&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Although the process for these 3 approaches may slightly differ, they all lead to the exact same conclusions. Using one method or another is, therefore, more often than not a matter of personal choice or a matter of context. See this &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#which-method-to-choose&#34;&gt;section&lt;/a&gt; to know which method I use depending on the context.&lt;/p&gt;
&lt;p&gt;I present the 3 methods in the following sections, starting with, in my opinion, the most comprehensive one when it comes to doing it by hand: comparing the test statistic with the critical value.&lt;/p&gt;
&lt;p&gt;For the three methods, I will explain the required steps to perform a hypothesis test from a general point of view and illustrate them with the following situation:&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Suppose a health professional who would like to test whether the mean weight of Belgian adults is different than 80 kg.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Note that, as for most hypothesis tests, the test we are going to use as example below requires some assumptions. Since the aim of the present article is to explain a hypothesis test, we assume that all assumptions are met. For the interested reader, see the assumptions (and how to verify them) for this type of hypothesis test in the article presenting the &lt;a href=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r-test-on-one-mean/#assumptions&#34;&gt;one-sample t-test&lt;/a&gt;.&lt;/p&gt;
&lt;div id=&#34;method-a-comparing-the-test-statistic-with-the-critical-value&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Method A: Comparing the test statistic with the critical value&lt;/h3&gt;
&lt;p&gt;Method A, which consists in comparing the test statistic with the critical value, boils down to the following 4 steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Stating the &lt;strong&gt;null and alternative hypothesis&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Computing the &lt;strong&gt;test statistic&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Finding the &lt;strong&gt;critical value&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Concluding&lt;/strong&gt; and interpreting the results&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Each step is detailed below.&lt;/p&gt;
&lt;div id=&#34;step-1-stating-the-null-and-alternative-hypothesis&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Step #1: Stating the null and alternative hypothesis&lt;/h4&gt;
&lt;p&gt;As discussed before, a hypothesis test first requires an idea, that is, an assumption about a phenomenon. This assumption, referred as hypothesis, is derived from the theory and/or the research question.&lt;/p&gt;
&lt;p&gt;Since a hypothesis test is used to confirm or refute a prior belief, we need to &lt;strong&gt;formulate our belief so that there is a null and an alternative hypothesis&lt;/strong&gt;. Those hypotheses must be &lt;a href=&#34;https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/#union-of-two-events&#34;&gt;mutually exclusive&lt;/a&gt;, which means that they cannot be true at the same time. This is step #1.&lt;/p&gt;
&lt;p&gt;In the context of our scenario, the null and alternative hypothesis are thus:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Null hypothesis &lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu = 80\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Alternative hypothesis &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu \ne 80\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When stating the null and alternative hypothesis, bear in mind the following three points:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;em&gt;We are always interested in the population and not in the sample.&lt;/em&gt; This is the reason &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt; will always be written in terms of the population and not in terms of the sample (in this case, &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; and not &lt;span class=&#34;math inline&#34;&gt;\(\bar{x}\)&lt;/span&gt;).&lt;/li&gt;
&lt;li&gt;&lt;em&gt;The assumption we would like to test is often the alternative hypothesis.&lt;/em&gt; If the researcher wanted to test whether the mean weight of Belgian adults was less than 80 kg, she would have stated &lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu = 80\)&lt;/span&gt; (or equivalently, &lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu \ge 80\)&lt;/span&gt;) and &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu &amp;lt; 80\)&lt;/span&gt;.&lt;a href=&#34;#fn4&#34; class=&#34;footnote-ref&#34; id=&#34;fnref4&#34;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt; Do not mix the null with the alternative hypothesis, or the conclusions will be diametrically opposed!&lt;/li&gt;
&lt;li&gt;&lt;em&gt;The null hypothesis is often the status quo.&lt;/em&gt; For instance, suppose that a doctor wants to test whether the new treatment A is more efficient than the old treatment B. The status quo is that the new and old treatments are equally efficient. Assuming a larger value is better, she will then write &lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu_A = \mu_B\)&lt;/span&gt; (or equivalently, &lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu_A - \mu_B = 0\)&lt;/span&gt;) and &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu_A &amp;gt; \mu_B\)&lt;/span&gt; (or equivalently, &lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu_A - \mu_B &amp;gt; 0\)&lt;/span&gt;). On the opposite, if the lower the better, she would have written &lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu_A = \mu_B\)&lt;/span&gt; (or equivalently, &lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu_A - \mu_B = 0\)&lt;/span&gt;) and &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu_A &amp;lt; \mu_B\)&lt;/span&gt; (or equivalently, &lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu_A - \mu_B &amp;lt; 0\)&lt;/span&gt;).&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div id=&#34;step-2-computing-the-test-statistic&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Step #2: Computing the test statistic&lt;/h4&gt;
&lt;p&gt;The &lt;strong&gt;test statistic&lt;/strong&gt; (often called &lt;strong&gt;t-stat&lt;/strong&gt;) is, in some sense, a metric indicating &lt;strong&gt;how extreme the observations are compared to the null hypothesis&lt;/strong&gt;. The higher the t-stat (in absolute value), the more extreme the observations are.&lt;/p&gt;
&lt;p&gt;There are several formulas to compute the t-stat, with one formula for each type of hypothesis test—one or two means, one or two proportions, one or two variances. This means that there is a formula to compute the t-stat for a hypothesis test on one mean, another formula for a test on two means, another for a test on one proportion, etc.&lt;a href=&#34;#fn5&#34; class=&#34;footnote-ref&#34; id=&#34;fnref5&#34;&gt;&lt;sup&gt;5&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The only difficulty in this second step is to choose the appropriate formula. As soon as you know which formula to use based on the type of test, you simply have to apply it to the data. For the interested reader, see the different formulas to compute the t-stat for the most common tests in this &lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-201/&#34; target=&#34;_blank&#34;&gt;Shiny app&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Luckily, formulas for hypothesis tests on one and two means, and one and two proportions follow the same structure.&lt;/p&gt;
&lt;p&gt;Computing the test statistic for these tests is similar than &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#probabilities-and-standard-normal-distribution&#34;&gt;scaling&lt;/a&gt; a random variable (a process also knows as “standardization” or “normalization”) which consists in subtracting the mean from that random variable, and dividing the result by the standard deviation:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[Z = \frac{X - \mu}{\sigma}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For these 4 hypothesis tests (one/two means and one/two proportions), computing the test statistic is like scaling the estimator (computed from the sample) corresponding to the parameter of interest (in the population). So we basically subtract the target parameter from the point estimator and then divide the result by the standard error (which is equivalent to the standard deviation but for an estimator).&lt;/p&gt;
&lt;p&gt;If this is unclear, here is how the test statistic (denoted &lt;span class=&#34;math inline&#34;&gt;\(t_{obs}\)&lt;/span&gt;) is computed in our scenario (assuming that the variance of the population is unknown):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[t_{obs} = \frac{\bar{x} - \mu}{\frac{s}{\sqrt{n}}}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\bar{x}\)&lt;/span&gt; is the sample mean (i.e., the estimator)&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; is the mean under the null hypothesis (i.e., the target parameter)&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(s\)&lt;/span&gt; is the sample standard deviation&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is the sample size&lt;/li&gt;
&lt;li&gt;(&lt;span class=&#34;math inline&#34;&gt;\(\frac{s}{\sqrt{n}}\)&lt;/span&gt; is the standard error)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Notice the similarity between the formula of this test statistic and the formula used to standardize a random variable. This structure is the same for a test on two means, one proportion and two proportions, except that the estimator, the parameter and the standard error are, of course, slightly different for each type of test.&lt;/p&gt;
&lt;p&gt;Suppose that in our case we have a sample mean of 71 kg (&lt;span class=&#34;math inline&#34;&gt;\(\bar{x}\)&lt;/span&gt; = 71), a sample standard deviation of 13 kg (&lt;span class=&#34;math inline&#34;&gt;\(s\)&lt;/span&gt; = 13) and a sample size of 10 adults (&lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; = 10). Remember that the population mean (the mean under the null hypothesis) is 80 kg (&lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; = 80).&lt;/p&gt;
&lt;p&gt;The t-stat is thus:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[t_{obs} = \frac{\bar{x} - \mu}{\frac{s}{\sqrt{n}}} = \frac{71 - 80}{\frac{13}{\sqrt{10}}} = -2.189\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Although formulas are different depending on which parameter you are testing, the value found for the test statistic gives us an indication on how extreme our observations are.&lt;/p&gt;
&lt;p&gt;We keep this value of -2.189 in mind because it will be used again in step #4.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;step-3-finding-the-critical-value&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Step #3: Finding the critical value&lt;/h4&gt;
&lt;p&gt;Although the t-stat gives us an indication of how extreme our observations are, we cannot tell whether this “score of extremity” is &lt;em&gt;too&lt;/em&gt; extreme or not based on its value only.&lt;/p&gt;
&lt;p&gt;So, at this point, we cannot yet tell whether our data are too extreme or not. For this, we need to compare our t-stat with a threshold—referred as &lt;strong&gt;critical value&lt;/strong&gt;—given by the &lt;a href=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/&#34;&gt;probability distribution&lt;/a&gt; tables (and which can, of course, also be found with R).&lt;/p&gt;
&lt;p&gt;In the same way that the formula to compute the t-stat is different for each parameter of interest, the underlying probability distribution—and thus the statistical table—on which the critical value is based is also different for each target parameter. This means that, in addition to choosing the appropriate formula to compute the t-stat, we also need to select the appropriate probability distribution depending on the parameter we are testing.&lt;/p&gt;
&lt;p&gt;Luckily, there are only 4 different probability distributions for the 6 hypothesis tests covered in this article (one/two means, one/two proportions and one/two variances):&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#probabilities-and-standard-normal-distribution&#34;&gt;Standard Normal distribution&lt;/a&gt;:
&lt;ul&gt;
&lt;li&gt;test on one and two means with known population variance(s)&lt;/li&gt;
&lt;li&gt;test on two paired samples where the variance of the difference between the 2 samples &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2_D\)&lt;/span&gt; is known&lt;/li&gt;
&lt;li&gt;test on one and two proportions (given that some assumptions are met)&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Student distribution:
&lt;ul&gt;
&lt;li&gt;test on one and two means with &lt;em&gt;un&lt;/em&gt;known population variance(s)&lt;/li&gt;
&lt;li&gt;test on two paired samples where the variance of the difference between the 2 samples &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2_D\)&lt;/span&gt; is &lt;em&gt;un&lt;/em&gt;known&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Chi-square distribution:
&lt;ul&gt;
&lt;li&gt;test on one variance&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Fisher distribution:
&lt;ul&gt;
&lt;li&gt;test on two variances&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Each probability distribution also has its own parameters (up to two parameters for the 4 distribution considered here), defining its shape and/or location. Parameter(s) of a probability distribution can be seen as its DNA; meaning that the distribution is entirely defined by its parameter(s).&lt;/p&gt;
&lt;p&gt;Taking our initial scenario—a health professional who would like to test whether the mean weight of Belgian adults is different than 80 kg—as example.&lt;/p&gt;
&lt;p&gt;The underlying probability distribution of a test on one mean is either the standard Normal or the Student distribution, depending on whether the variance of the &lt;em&gt;population&lt;/em&gt; (not sample variance!) is known or unknown:&lt;a href=&#34;#fn6&#34; class=&#34;footnote-ref&#34; id=&#34;fnref6&#34;&gt;&lt;sup&gt;6&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If the population variance is known &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow\)&lt;/span&gt; the standard Normal distribution is used&lt;/li&gt;
&lt;li&gt;If the population variance is &lt;em&gt;un&lt;/em&gt;known &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow\)&lt;/span&gt; the Student distribution is used&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If no population variance is explicitly given, you can assume that it is unknown since you cannot compute it based on a sample. If you could compute it, that would mean you have access to the entire population and there is, in this case, no point in performing a hypothesis test (you could simply use some &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt; to confirm or refute your belief).&lt;/p&gt;
&lt;p&gt;In our example, no population variance is specified so it is assumed to be unknown. We therefore use the Student distribution.&lt;/p&gt;
&lt;p&gt;The Student distribution has one parameter which defines it; the number of degrees of freedom. The number of degrees of freedom depends on the type of hypothesis test. For instance, the number of degrees of freedom for a test on one mean is equal to the number of observations minus one (&lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; - 1). Without going too far into the details, the - 1 comes from the fact that there is one quantity which is estimated (i.e., the mean).&lt;a href=&#34;#fn7&#34; class=&#34;footnote-ref&#34; id=&#34;fnref7&#34;&gt;&lt;sup&gt;7&lt;/sup&gt;&lt;/a&gt; The sample size being equal to 10 in our example, the degrees of freedom is equal to &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; - 1 = 10 - 1 = 9.&lt;/p&gt;
&lt;p&gt;There is only one last element missing to find the critical value: the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/#a-note-on-p-value-and-significance-level-alpha&#34;&gt;significance level&lt;/a&gt;. The &lt;strong&gt;significance level&lt;/strong&gt;, denoted &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;, is the probability of wrongly rejecting the null hypothesis, so the &lt;strong&gt;probability of rejecting the null hypothesis although it is in reality true&lt;/strong&gt;. In this sense, it is an error (type I error, as opposed to the type II error&lt;a href=&#34;#fn8&#34; class=&#34;footnote-ref&#34; id=&#34;fnref8&#34;&gt;&lt;sup&gt;8&lt;/sup&gt;&lt;/a&gt;) that we accept to deal with, in order to be able to draw conclusions about a population based on a subset of it.&lt;/p&gt;
&lt;p&gt;As you may have read in many statistical textbooks, the significance level is very often set to 5%.&lt;a href=&#34;#fn9&#34; class=&#34;footnote-ref&#34; id=&#34;fnref9&#34;&gt;&lt;sup&gt;9&lt;/sup&gt;&lt;/a&gt; In some fields (such as medicine or engineering, among others), the significance level is also sometimes set to 1% to decrease the error rate.&lt;/p&gt;
&lt;p&gt;It is best to specify the significance level &lt;em&gt;before&lt;/em&gt; performing a hypothesis test to avoid the temptation to set the significance level in accordance to the results (the temptation is even bigger when the results are on the edge of being significant). As I always tell my students, you cannot “guess” nor compute the significance level. Therefore, if it is not explicitly specified, you can safely assume it is 5%. In our case, we did not indicate it, so we take &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; = 5% = 0.05.&lt;/p&gt;
&lt;p&gt;Furthermore, in our example, we want to test whether the mean weight of Belgian adults is &lt;strong&gt;different&lt;/strong&gt; than 80 kg. Since we do not specify the direction of the test, it is a &lt;strong&gt;two-sided test&lt;/strong&gt;. If we wanted to test that the mean weight was less than 80 kg (&lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu &amp;lt;\)&lt;/span&gt; 80) or greater than 80 kg (&lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu &amp;gt;\)&lt;/span&gt; 80), we would have done a one-sided test.&lt;/p&gt;
&lt;p&gt;Make sure that you perform the correct test (two-sided or one-sided) because it has an impact on how to find the critical value (see more in the following paragraphs).&lt;/p&gt;
&lt;p&gt;So now that we know the appropriate distribution (Student distribution), its parameter (degrees of freedom (df) = 9), the significance level (&lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; = 0.05) and the direction (two-sided), we have all we need to find the critical value in the &lt;a href=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/&#34;&gt;statistical tables&lt;/a&gt;:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2021-01-27-hypothesis-test-by-hand_files/critical_value_student_distribution.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;By looking at the row df = 9 and the column &lt;span class=&#34;math inline&#34;&gt;\(t_.025\)&lt;/span&gt; in the Student’s distribution table, we find a critical value of:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[t_{n-1; \alpha / 2} = t_{9; 0.025} = 2.262\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;One may wonder why we take &lt;span class=&#34;math inline&#34;&gt;\(t_{\alpha/2} = t_.025\)&lt;/span&gt; and not &lt;span class=&#34;math inline&#34;&gt;\(t_\alpha = t_.05\)&lt;/span&gt; since the significance level is 0.05. The reason is that we are doing a two-sided test (&lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu \ne\)&lt;/span&gt; 80), so the error rate of 0.05 must be divided in 2 to find the critical value to the right of the distribution. Since the Student’s distribution is symmetric, the critical value to the left of the distribution is simply: -2.262.&lt;/p&gt;
&lt;p&gt;Visually, the error rate of 0.05 is partitioned into two parts:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;0.025 to the left of -2.262 and&lt;/li&gt;
&lt;li&gt;0.025 to the right of 2.262&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2021-01-27-hypothesis-test-by-hand_files/figure-html/unnamed-chunk-1-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;We keep in mind these critical values of -2.262 and 2.262 for the fourth and last step.&lt;/p&gt;
&lt;p&gt;Note that the red shaded areas in the previous plot are also known as the rejection regions. More on that in the following section.&lt;/p&gt;
&lt;p&gt;These critical values can also be found in R, thanks to the &lt;code&gt;qt()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;qt(0.025, df = 9, lower.tail = TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] -2.262157&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;qt(0.025, df = 9, lower.tail = FALSE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 2.262157&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;qt()&lt;/code&gt; function is used for the Student’s distribution (&lt;code&gt;q&lt;/code&gt; stands for quantile and &lt;code&gt;t&lt;/code&gt; for Student). There are other functions accompanying the different distributions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;qnorm()&lt;/code&gt; for the Normal distribution&lt;/li&gt;
&lt;li&gt;&lt;code&gt;qchisq()&lt;/code&gt; for the Chi-square distribution&lt;/li&gt;
&lt;li&gt;&lt;code&gt;qf()&lt;/code&gt; for the Fisher distribution&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;step-4-concluding-and-interpreting-the-results&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Step #4: Concluding and interpreting the results&lt;/h4&gt;
&lt;p&gt;In this fourth and last step, all we have to do is to &lt;strong&gt;compare the test statistic&lt;/strong&gt; (computed in step #2) &lt;strong&gt;with the critical values&lt;/strong&gt; (found in step #3) in order to &lt;strong&gt;conclude the hypothesis test&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The only two possibilities when concluding a hypothesis test are:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Rejection of the null hypothesis&lt;/li&gt;
&lt;li&gt;Non-rejection of the null hypothesis&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In our example of adult weight, remember that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the t-stat is -2.189&lt;/li&gt;
&lt;li&gt;the critical values are -2.262 and 2.262&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Also remember that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the &lt;strong&gt;t-stat gives an indication on how extreme our sample is&lt;/strong&gt; compared to the null hypothesis&lt;/li&gt;
&lt;li&gt;the &lt;strong&gt;critical values are the threshold from which the t-stat is considered as &lt;em&gt;too&lt;/em&gt; extreme&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;To compare the t-stat with the critical values, I always recommend to plot them:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2021-01-27-hypothesis-test-by-hand_files/figure-html/unnamed-chunk-3-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;These two critical values form the rejection regions (the red shaded areas):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;from &lt;span class=&#34;math inline&#34;&gt;\(- \infty\)&lt;/span&gt; to -2.262, and&lt;/li&gt;
&lt;li&gt;from 2.262 to &lt;span class=&#34;math inline&#34;&gt;\(\infty\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If the &lt;strong&gt;t-stat lies within one of the rejection region, we reject the null hypothesis&lt;/strong&gt;. On the contrary, if the &lt;strong&gt;t-stat does &lt;em&gt;not&lt;/em&gt; lie within any of the rejection region, we do &lt;em&gt;not&lt;/em&gt; reject the null hypothesis&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;As we can see from the above plot, the t-stat is less extreme than the critical value and therefore does not lie within any of the rejection region. In conclusion, we do not reject the null hypothesis that &lt;span class=&#34;math inline&#34;&gt;\(\mu = 80\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;This is the conclusion in statistical terms but they are meaningless without proper interpretation. So it is a good practice to also interpret the result in the context of the problem:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;At the 5% significance level, we do not reject the hypothesis that the mean weight of Belgian adults is 80 kg.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;div id=&#34;why-dont-we-accept-h_0&#34; class=&#34;section level5&#34;&gt;
&lt;h5&gt;Why don’t we accept &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;?&lt;/h5&gt;
&lt;p&gt;From a more philosophical (but still very important) perspective, note that we wrote “we &lt;em&gt;do not reject&lt;/em&gt; the null hypothesis” and “we &lt;em&gt;do not reject&lt;/em&gt; the hypothesis that the mean weight of Belgian adults is equal to 80 kg”. We did not write “we &lt;em&gt;accept&lt;/em&gt; the null hypothesis” nor “the mean weight of Belgian adults is 80 kg”.&lt;/p&gt;
&lt;p&gt;The reason is due to the fact that, in hypothesis testing, we conclude something about the population based on a sample. There is, therefore, always some uncertainty and we cannot be 100% sure that our conclusion is correct.&lt;/p&gt;
&lt;p&gt;Perhaps it is the case that the mean weight of Belgian adults is in reality different than 80 kg, but &lt;strong&gt;we failed to prove it&lt;/strong&gt; based on the data at hand. It may be the case that if we had more observations, we would have rejected the null hypothesis (since all else being equal, a larger sample size implies a more extreme t-stat). Or, it may be the case that even with more observations, we would not have rejected the null hypothesis because the mean weight of Belgian adults is in reality close to 80 kg. We cannot distinguish between the two.&lt;/p&gt;
&lt;p&gt;So we can just say that we did not find enough evidence against the hypothesis that the mean weight of Belgian adults is 80 kg, but we do not conclude that the mean is equal to 80 kg.&lt;/p&gt;
&lt;p&gt;If the difference is still not clear to you, the following example may help. Suppose a person is suspected of having committed a crime. This person is either innocent—the null hypothesis—or guilty—the alternative hypothesis. In the attempt to know if the suspect committed the crime, the police collects as much information and proof as possible. This is similar to the researcher collecting data to form a sample. And then the judge, based on the collected evidence, decides whether the suspect is considered as innocent or guilty. If there is enough evidence that the suspect committed the crime, the judge will conclude that the suspect is guilty. In other words, she will reject the null hypothesis of the suspect being innocent because there are enough evidence that the suspect committed the crime.&lt;/p&gt;
&lt;p&gt;This is similar to the t-stat being more extreme than the critical value: we have enough information (based on the sample) to say that the null hypothesis is unlikely because our data would be too extreme if the null hypothesis were true. Since the sample cannot be “wrong” (it corresponds to the collected data), the only remaining possibility is that the null hypothesis is in fact wrong. This is the reason we write “we reject the null hypothesis”.&lt;/p&gt;
&lt;p&gt;On the other hand, if there is not enough evidence that the suspect committed the crime (or no evidence at all), the judge will conclude that the suspect is considered as not guilty. In other words, she will not reject the null hypothesis of the suspect being innocent. But even if she concludes that the suspect is considered as not guilty, she will never be 100% sure that he is really innocent.&lt;/p&gt;
&lt;p&gt;It may be the case that:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;the suspect did not commit the crime, or&lt;/li&gt;
&lt;li&gt;the suspect committed the crime but the police was not able to collect enough information against the suspect.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In the former case the suspect is really innocent, whereas in the latter case the suspect is guilty but the police and the judge failed to prove it because they failed to find enough evidence against him. Similar to hypothesis testing, the judge has to conclude the case by considering the suspect not guilty, without being able to distinguish between the two.&lt;/p&gt;
&lt;p&gt;This is the main reason we write “we do not reject the null hypothesis” or “we fail to reject the null hypothesis” (you may even read in some textbooks conclusion such as “there is no sufficient evidence in the data to reject the null hypothesis”), and we do not write “we accept the null hypothesis”.&lt;/p&gt;
&lt;p&gt;I hope this metaphor helped you to understand the reason why we reject the null hypothesis instead of accepting it.&lt;/p&gt;
&lt;p&gt;In the following sections, we present two other methods used in hypothesis testing.&lt;/p&gt;
&lt;p&gt;These methods will result in the exact same conclusion: non-rejection of the null hypothesis, that is, we do not reject the hypothesis that the mean weight of Belgian adults is 80 kg. It is thus presented only if you prefer to use these methods over the first one.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;method-b-comparing-the-p-value-with-the-significance-level-alpha&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Method B: Comparing the &lt;em&gt;p&lt;/em&gt;-value with the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Method B, which consists in computing the &lt;em&gt;p&lt;/em&gt;-value and comparing this &lt;em&gt;p&lt;/em&gt;-value with the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;, boils down to the following 4 steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Stating the &lt;strong&gt;null and alternative hypothesis&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Computing the &lt;strong&gt;test statistic&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Computing the &lt;strong&gt;&lt;em&gt;p&lt;/em&gt;-value&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Concluding&lt;/strong&gt; and interpreting the results&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In this second method which uses the &lt;em&gt;p&lt;/em&gt;-value, the first and second steps are similar than in the first method.&lt;/p&gt;
&lt;div id=&#34;step-1-stating-the-null-and-alternative-hypothesis-1&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Step #1: Stating the null and alternative hypothesis&lt;/h4&gt;
&lt;p&gt;The null and alternative hypotheses remain the same:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu = 80\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu \ne 80\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;step-2-computing-the-test-statistic-1&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Step #2: Computing the test statistic&lt;/h4&gt;
&lt;p&gt;Remember that the formula for the t-stat is different depending on the type of hypothesis test (one or two means, one or two proportions, one or two variances). In our case of one mean with unknown variance, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[t_{obs} = \frac{\bar{x} - \mu}{\frac{s}{\sqrt{n}}} = \frac{71 - 80}{\frac{13}{\sqrt{10}}} = -2.189\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;step-3-computing-the-p-value&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Step #3: Computing the &lt;em&gt;p&lt;/em&gt;-value&lt;/h4&gt;
&lt;p&gt;The &lt;strong&gt;&lt;em&gt;p&lt;/em&gt;-value&lt;/strong&gt; is the &lt;a href=&#34;https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/&#34;&gt;probability&lt;/a&gt; (so it goes from 0 to 1) of observing a sample at least as extreme as the one we observed if the null hypothesis were true. In some sense, it &lt;strong&gt;gives you an indication on how likely your null hypothesis is&lt;/strong&gt;. It is also defined as the smallest level of significance for which the data indicate rejection of the null hypothesis.&lt;/p&gt;
&lt;p&gt;For more information about the &lt;em&gt;p&lt;/em&gt;-value, I recommend reading this &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/#a-note-on-p-value-and-significance-level-alpha&#34;&gt;note about the &lt;em&gt;p&lt;/em&gt;-value and the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Formally, the &lt;em&gt;p&lt;/em&gt;-value is the area beyond the test statistic. Since we are doing a two-sided test, the &lt;em&gt;p&lt;/em&gt;-value is thus the sum of the area above 2.189 and below -2.189.&lt;/p&gt;
&lt;p&gt;Visually, the &lt;em&gt;p&lt;/em&gt;-value is the sum of the two blue shaded areas in the following plot:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2021-01-27-hypothesis-test-by-hand_files/figure-html/unnamed-chunk-4-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value can computed with precision in R with the &lt;code&gt;pt()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;p_val &amp;lt;- pt(-2.189, df = 9, lower.tail = TRUE) + pt(2.189, df = 9, lower.tail = FALSE)
p_val&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.05634202&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# which is equivalent than:
p_val &amp;lt;- 2 * pt(2.189, df = 9, lower.tail = FALSE)
p_val&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.05634202&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.0563, which indicates that there is a 5.63% chance to observe a sample at least as extreme as the one observed if the null hypothesis were true. This already gives us a hint on whether our t-stat is too extreme or not (and thus whether our null hypothesis is likely or not), but we formally conclude in step #4.&lt;/p&gt;
&lt;p&gt;Like the &lt;code&gt;qt()&lt;/code&gt; function to find the critical value, we use &lt;code&gt;pt()&lt;/code&gt; to find the &lt;em&gt;p&lt;/em&gt;-value because the underlying distribution is the Student’s distribution.&lt;/p&gt;
&lt;p&gt;Use &lt;code&gt;pnorm()&lt;/code&gt;, &lt;code&gt;pchisq()&lt;/code&gt; and &lt;code&gt;pf()&lt;/code&gt; for the Normal, Chi-square and Fisher distribution, respectively. See also this &lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-101/&#34; target=&#34;_blank&#34;&gt;Shiny app&lt;/a&gt; to compute the &lt;em&gt;p&lt;/em&gt;-value given a certain t-stat for most probability distributions.&lt;/p&gt;
&lt;p&gt;If you do not have access to a computer (during exams for example) you will not be able to compute the &lt;em&gt;p&lt;/em&gt;-value precisely, but you can bound it using the statistical table referring to your test.&lt;/p&gt;
&lt;p&gt;In our case, we use the Student distribution and we look at the row df = 9 (since df = &lt;em&gt;n&lt;/em&gt; - 1):&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2021-01-27-hypothesis-test-by-hand_files/p-value-student-distribution.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;The test statistic is -2.189&lt;/li&gt;
&lt;li&gt;We take the absolute value, which gives 2.189&lt;/li&gt;
&lt;li&gt;The value 2.189 is between 1.833 and 2.262 (highlighted in blue in the above table)&lt;/li&gt;
&lt;li&gt;From the column names &lt;span class=&#34;math inline&#34;&gt;\(t_{.050}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(t_{.025}\)&lt;/span&gt; related to 1.833 and 2.262, we know that:
&lt;ul&gt;
&lt;li&gt;the area to the right of 1.833 is 0.05&lt;/li&gt;
&lt;li&gt;the area to the right of 2.262 is 0.025&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;So we know that the area to the right of 2.189 must be between 0.025 and 0.05&lt;/li&gt;
&lt;li&gt;Since the Student distribution is symmetric, we know that the area to the left of -2.189 must also be between 0.025 and 0.05&lt;/li&gt;
&lt;li&gt;Therefore, the sum of the two areas must be between 0.05 and 0.10&lt;/li&gt;
&lt;li&gt;In other words, the &lt;em&gt;p&lt;/em&gt;-value is between 0.05 and 0.10 (i.e., 0.05 &amp;lt; &lt;em&gt;p&lt;/em&gt;-value &amp;lt; 0.10)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Although we could not compute it precisely, it is enough to conclude our hypothesis test in the last step.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;step-4-concluding-and-interpreting-the-results-1&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Step #4: Concluding and interpreting the results&lt;/h4&gt;
&lt;p&gt;The final step is now to simply compare the &lt;em&gt;p&lt;/em&gt;-value (computed in step #3) with the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;. As for all &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If the &lt;strong&gt;&lt;em&gt;p&lt;/em&gt;-value is smaller&lt;/strong&gt; than &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; (&lt;em&gt;p&lt;/em&gt;-value &amp;lt; 0.05) &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow H_0\)&lt;/span&gt; is unlikely &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow\)&lt;/span&gt; we &lt;strong&gt;reject&lt;/strong&gt; the null hypothesis&lt;/li&gt;
&lt;li&gt;If the &lt;strong&gt;&lt;em&gt;p&lt;/em&gt;-value is greater&lt;/strong&gt; than or equal to &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; (&lt;em&gt;p&lt;/em&gt;-value &lt;span class=&#34;math inline&#34;&gt;\(\ge\)&lt;/span&gt; 0.05) &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow H_0\)&lt;/span&gt; is likely &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow\)&lt;/span&gt; we do &lt;strong&gt;not reject&lt;/strong&gt; the null hypothesis&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;No matter if we take into consideration the exact &lt;em&gt;p&lt;/em&gt;-value (i.e., 0.0563) or the bounded one (0.05 &amp;lt; &lt;em&gt;p&lt;/em&gt;-value &amp;lt; 0.10), it is larger than 0.05, so we do not reject the null hypothesis.&lt;a href=&#34;#fn10&#34; class=&#34;footnote-ref&#34; id=&#34;fnref10&#34;&gt;&lt;sup&gt;10&lt;/sup&gt;&lt;/a&gt; In the context of the problem, we do not reject the null hypothesis that the mean weight of Belgian adults is 80 kg.&lt;/p&gt;
&lt;p&gt;Remember that rejecting (or not rejecting) a null hypothesis at the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; using the critical value method (method A) is equivalent to rejecting (or not rejecting) the null hypothesis when the &lt;em&gt;p&lt;/em&gt;-value is lower (equal or greater) than &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; (method B).&lt;/p&gt;
&lt;p&gt;This is the reason we find the exact same conclusion than with method A, and why you should too if you use both methods on the same data and with the same significance level.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;method-c-comparing-the-target-parameter-with-the-confidence-interval&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Method C: Comparing the target parameter with the confidence interval&lt;/h3&gt;
&lt;p&gt;Method C, which consists in computing the confidence interval and comparing this confidence interval with the target parameter (the parameter under the null hypothesis), boils down to the following 3 steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Stating the &lt;strong&gt;null and alternative hypothesis&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Computing the &lt;strong&gt;confidence interval&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Concluding&lt;/strong&gt; and interpreting the results&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In this last method which uses the confidence interval, the first step is similar than in the first two methods.&lt;/p&gt;
&lt;div id=&#34;step-1-stating-the-null-and-alternative-hypothesis-2&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Step #1: Stating the null and alternative hypothesis&lt;/h4&gt;
&lt;p&gt;The null and alternative hypotheses remain the same:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu = 80\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu \ne 80\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;step-2-computing-the-confidence-interval&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Step #2: Computing the confidence interval&lt;/h4&gt;
&lt;p&gt;Like hypothesis testing, confidence intervals are a well-known tool in inferential statistics.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Confidence interval is&lt;/strong&gt; an estimation procedure which produces &lt;strong&gt;an interval&lt;/strong&gt; (i.e., a range of values) &lt;strong&gt;containing the true parameter with a certain&lt;/strong&gt;—usually high—&lt;strong&gt;probability&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In the same way that there is a formula for each type of hypothesis test when computing the test statistics, there exists a formula for each type of confidence interval. Formulas for the different types of confidence intervals can be found in this &lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-201/&#34; target=&#34;_blank&#34;&gt;Shiny app&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Here is the formula for a confidence interval on one mean &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; (with unknown population variance):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
(1-\alpha)\text{% CI for } \mu = \bar{x} \pm t_{\alpha/2, n - 1} \frac{s}{\sqrt{n}}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(t_{\alpha/2, n - 1}\)&lt;/span&gt; is found in the Student distribution table (and is similar to the critical value found in step #3 of method A).&lt;/p&gt;
&lt;p&gt;Given our data and with &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; = 0.05, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
\begin{aligned}
95\text{% CI for } \mu &amp;amp;= \bar{x} \pm t_{\alpha/2, n - 1} \frac{s}{\sqrt{n}} \\
&amp;amp;= 71 \pm 2.262 \frac{13}{\sqrt{10}} \\
&amp;amp;= [61.70; 80.30]
\end{aligned}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The 95% confidence interval for &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; is [61.70; 80.30] kg. But &lt;strong&gt;what does a 95% confidence interval mean?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We know that this estimation procedure has a 95% probability of producing an interval containing the true mean &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt;. In other words, &lt;strong&gt;if we construct many confidence intervals&lt;/strong&gt; (with different samples of the same size), &lt;strong&gt;95% of them will&lt;/strong&gt;, on average, &lt;strong&gt;include the mean of the population&lt;/strong&gt; (the true parameter). So on average, 5% of these confidence intervals will not cover the true mean.&lt;/p&gt;
&lt;p&gt;If you wish to decrease this last percentage, you can decrease the significance level (set &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; = 0.01 or 0.02 for instance). All else being equal, this will increase the range of the confidence interval and thus increase the probability that it includes the true parameter.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;step-3-concluding-and-interpreting-the-results&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Step #3: Concluding and interpreting the results&lt;/h4&gt;
&lt;p&gt;The final step is simply to compare the confidence interval (constructed in step #2) with the value of the target parameter (the value under the null hypothesis, mentioned in step #1):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If the &lt;strong&gt;confidence interval does not include&lt;/strong&gt; the hypothesized value &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow H_0\)&lt;/span&gt; is unlikely &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow\)&lt;/span&gt; we &lt;strong&gt;reject&lt;/strong&gt; the null hypothesis&lt;/li&gt;
&lt;li&gt;If the &lt;strong&gt;confidence interval includes&lt;/strong&gt; the hypothesized value &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow H_0\)&lt;/span&gt; is likely &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow\)&lt;/span&gt; we do &lt;strong&gt;not reject&lt;/strong&gt; the null hypothesis&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In our example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the hypothesized value is 80 (since &lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu\)&lt;/span&gt; = 80)&lt;/li&gt;
&lt;li&gt;80 is included in the 95% confidence interval since it goes from 61.70 to 80.30 kg&lt;/li&gt;
&lt;li&gt;So we do not reject the null hypothesis&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In the terms of the problem, we do not reject the hypothesis that the mean weight of Belgian adults is 80 kg.&lt;/p&gt;
&lt;p&gt;As you can see, the conclusion is equivalent than with the critical value method (method A) and the &lt;em&gt;p&lt;/em&gt;-value method (method B). Again, this must be the case since we use the same data and the same significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; for all three methods.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;which-method-to-choose&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Which method to choose?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;All three methods give the same conclusion.&lt;/strong&gt; However, each method has its own advantage so I usually select the most convenient one depending on the situation:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Method A (comparing the test statistic with the critical value):
&lt;ul&gt;
&lt;li&gt;It is, in my opinion, the &lt;strong&gt;easiest and most straightforward method&lt;/strong&gt; of the three when I do not have access to R.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Method B (comparing the &lt;em&gt;p&lt;/em&gt;-value with the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;):
&lt;ul&gt;
&lt;li&gt;In addition to being able to know whether the null hypothesis is rejected or not, computing the &lt;strong&gt;exact &lt;em&gt;p&lt;/em&gt;-value can be very convenient&lt;/strong&gt; so I tend to use this method if I have access to R.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Method C (comparing the target parameter with the confidence interval):
&lt;ul&gt;
&lt;li&gt;If I need to test &lt;strong&gt;several hypothesized values&lt;/strong&gt;, I tend to choose this method because I can construct one single confidence interval and compare it to as many values as I want. For example, with our 95% confidence interval [61.70; 80.30], I know that any value below 61.70 kg and above 80.30 kg will be rejected, without testing it for each value.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;summary&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;In this article, we reviewed the &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#why&#34;&gt;goals&lt;/a&gt; and &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#when&#34;&gt;when&lt;/a&gt; hypothesis testing is used. We then showed &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#how&#34;&gt;how to do a hypothesis test by hand&lt;/a&gt; through three different methods (A. &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#method-a-comparing-the-test-statistic-with-the-critical-value&#34;&gt;critical value&lt;/a&gt;, B. &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#method-b-comparing-the-p-value-with-the-significance-level-alpha&#34;&gt;&lt;em&gt;p&lt;/em&gt;-value&lt;/a&gt; and C. &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#method-c-comparing-the-target-parameter-with-the-confidence-interval&#34;&gt;confidence interval&lt;/a&gt;). We also showed how to &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#step-4-concluding-and-interpreting-the-results&#34;&gt;interpret the results&lt;/a&gt; in the context of the initial problem.&lt;/p&gt;
&lt;p&gt;Although all three methods give the exact same conclusion when using the same data and the same significance level (otherwise there is a mistake somewhere), I also presented my personal &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#which-method-to-choose&#34;&gt;preferences&lt;/a&gt; when it comes to choosing one method over the other two.&lt;/p&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to understand the structure of a hypothesis by hand. I remind you that, at least for the 6 hypothesis tests covered in this article, the formulas are different, but the structure and the reasoning behind it remain the same. So you basically have to know which formulas to use, and simply follow the steps mentioned in this article.&lt;/p&gt;
&lt;p&gt;For the interested reader, I created two accompanying Shiny apps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-201/&#34; target=&#34;_blank&#34;&gt;Hypothesis testing and confidence intervals&lt;/a&gt;: after entering your data, the app illustrates all the steps in order to conclude the test and compute a confidence interval. See more information in this &lt;a href=&#34;https://statsandr.com/blog/a-shiny-app-for-inferential-statistics-by-hand/&#34;&gt;article&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-101/&#34; target=&#34;_blank&#34;&gt;How to read statistical tables&lt;/a&gt;: the app helps you to compute the &lt;em&gt;p&lt;/em&gt;-value given a t-stat for most probability distributions. See more information in this &lt;a href=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/&#34;&gt;article&lt;/a&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;Suppose a researcher wants to test whether Belgian women are taller than French women. Suppose a health professional would like to know whether the proportion of smokers is different among athletes and non-athletes. It would take way too long to measure the height of all Belgian and French women and to ask all athletes and non-athletes their smoking habits. So most of the time, decisions are based on a representative sample of the population and not on the whole population. If we could measure the entire population in a reasonable time frame, we would not do any inferential statistics.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Don’t get me wrong, this does not mean that hypothesis tests are &lt;em&gt;never&lt;/em&gt; used in exploratory analyses. It is just much less frequent in exploratory research than in confirmatory research.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;You may see more or less steps in other articles or textbooks, depending on whether these steps are detailed or concise. Hypothesis testing should, however, follows the same process regardless of the number of steps.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;For one-sided tests, writing &lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu = 80\)&lt;/span&gt; or &lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu \ge 80\)&lt;/span&gt; are both correct. The point is that the null and alternative hypothesis must be mutually exclusive since you are testing one hypothesis against the other, so both cannot be true at the same time.&lt;a href=&#34;#fnref4&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn5&#34;&gt;&lt;p&gt;To be complete, there are even different formulas within each type of test, depending on whether some assumptions are met or not. For the interested reader, see all the different scenarios and thus the different formulas for a test on &lt;a href=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r-test-on-one-mean/&#34;&gt;one mean&lt;/a&gt; and on &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;two means&lt;/a&gt;.&lt;a href=&#34;#fnref5&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn6&#34;&gt;&lt;p&gt;There are more uncertainty if the population variance is unknown than if it is known, and this greater uncertainty is taken into account by using the Student distribution instead of the standard Normal distribution. Also note that as the sample size increases, the degrees of freedom of the Student distribution increases and the two distributions become more and more similar. For large sample size (usually from &lt;span class=&#34;math inline&#34;&gt;\(n &amp;gt;\)&lt;/span&gt; 30), the Student distribution becomes so close to the standard Normal distribution that, even if the population variance is unknown, the standard Normal distribution can be used.&lt;a href=&#34;#fnref6&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn7&#34;&gt;&lt;p&gt;For a test on two independent samples, the degrees of freedom is &lt;span class=&#34;math inline&#34;&gt;\(n_1 + n_2 - 2\)&lt;/span&gt;, where &lt;span class=&#34;math inline&#34;&gt;\(n_1\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(n_2\)&lt;/span&gt; are the size of the first and second sample, respectively. Note the - 2 due to the fact that in this case, two quantities are estimated.&lt;a href=&#34;#fnref7&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn8&#34;&gt;&lt;p&gt;The type II error is the probability of not rejecting the null hypothesis although it is in reality false.&lt;a href=&#34;#fnref8&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn9&#34;&gt;&lt;p&gt;Whether this is a good or a bad standard is a question that comes up often and is debatable. This is, however, beyond the scope of the article.&lt;a href=&#34;#fnref9&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn10&#34;&gt;&lt;p&gt;Again, &lt;em&gt;p&lt;/em&gt;-values found via a statistical table or via R must be coherent.&lt;a href=&#34;#fnref10&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Paper: &#39;Waiting period from diagnosis for mortgage insurance issued to cancer survivors&#39;</title>
      <link>https://statsandr.com/blog/waiting-period-cancer-survivors/</link>
      <pubDate>Mon, 23 Nov 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/waiting-period-cancer-survivors/</guid>
      <description>


&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-11-23-waiting-period-cancer-survivors_files/waiting-period-cancer-survivors.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;I am happy to announce that our paper entitled “&lt;a href=&#34;https://rdcu.be/cbagv&#34; target=&#34;_blank&#34;&gt;Waiting period from diagnosis for mortgage insurance issued to cancer survivors&lt;/a&gt;” has been published in the European Actuarial Journal &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-soetewey2021waiting&#34; role=&#34;doc-biblioref&#34;&gt;Soetewey et al. 2021&lt;/a&gt;)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Here is a brief &lt;strong&gt;summary&lt;/strong&gt; of it:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;
Massart (2018) testimonial illustrates the difficulties faced by patients having survived cancer to access mortgage insurance securing home loan. Data collected by national registries nevertheless suggest that excess mortality due to some types of cancer becomes moderate or even negligible after some waiting period.
&lt;/p&gt;
&lt;p&gt;
In relation to the insurance laws passed in France and more recently in Belgium creating a right to be forgotten for cancer survivors, the present study aims to determine the waiting period after which standard premium rates become applicable. Compared to the French and Belgian laws, a waiting period starting at diagnosis (as recorded in national databases) is favored over a waiting period starting at the end of the therapeutic treatment protocol. This aims to avoid disputes when a claim is filed. Since diagnosis is often recorded in the official registry database, as is the case for the Belgian Cancer Registry, its date is reliable and unquestionable in case of claim.
&lt;/p&gt;
&lt;p&gt;
Based on 28,994 melanoma and thyroid cancer cases recorded by the Belgian Cancer Registry, the length of the waiting period is assessed with the help of widely-accepted tools from biostatistics, including relative survival models and time-to-cure indicators. It turns out for instance that a waiting period of 4 years after diagnosis is enough for 30-year-old thyroid cancer patients. This appears to be similar to the 3-year period starting at the end of treatment protocol according to the Belgian law in such a case.
&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Read the full article &lt;a href=&#34;https://rdcu.be/cbagv&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Here is a video explaining the paper and our research in general:&lt;/p&gt;
&lt;center&gt;
&lt;iframe width=&#34;560&#34; height=&#34;315&#34; src=&#34;https://www.youtube.com/embed/qQrVV3prEDU&#34; frameborder=&#34;0&#34; allow=&#34;accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture&#34; allowfullscreen&gt;
&lt;/iframe&gt;
&lt;/center&gt;
&lt;p&gt;The paper also led to a &lt;a href=&#34;https://www.antoinesoetewey.com/files/Journee_modeles_de_guerison.pdf&#34; target=&#34;_blank&#34;&gt;talk&lt;/a&gt; organized by the French National Cancer Institute (INCa).&lt;/p&gt;
&lt;p&gt;&lt;em&gt;This paper is written jointly with Prof. Catherine Legrand and Prof. Michel Denuit—my PhD supervisors—and Dr. Geert Silversmit from the Belgian Cancer Registry.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Thanks for reading. I hope this paper will, to some extent, be helpful for your research.&lt;/p&gt;
&lt;p&gt;As always, if you have any question related to the topic covered in this paper, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;div id=&#34;references&#34; class=&#34;section level2 unnumbered&#34;&gt;
&lt;h2&gt;References&lt;/h2&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-soetewey2021waiting&#34; class=&#34;csl-entry&#34;&gt;
Soetewey, Antoine, Catherine Legrand, Michel Denuit, and Geert Silversmit. 2021. &lt;span&gt;“Waiting Period from Diagnosis for Mortgage Insurance Issued to Cancer Survivors.”&lt;/span&gt; &lt;em&gt;European Actuarial Journal&lt;/em&gt; 11: 135–60. &lt;a href=&#34;https://doi.org/10.1007/s13385-020-00254-x&#34;&gt;https://doi.org/10.1007/s13385-020-00254-x&lt;/a&gt;.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>ANOVA in R</title>
      <link>https://statsandr.com/blog/anova-in-r/</link>
      <pubDate>Mon, 12 Oct 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/anova-in-r/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#data&#34; id=&#34;toc-data&#34;&gt;Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#aim-and-hypotheses-of-anova&#34; id=&#34;toc-aim-and-hypotheses-of-anova&#34;&gt;Aim and hypotheses of ANOVA&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#underlying-assumptions-of-anova&#34; id=&#34;toc-underlying-assumptions-of-anova&#34;&gt;Underlying assumptions of ANOVA&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#variable-type&#34; id=&#34;toc-variable-type&#34;&gt;Variable type&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#independence&#34; id=&#34;toc-independence&#34;&gt;Independence&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#normality&#34; id=&#34;toc-normality&#34;&gt;Normality&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#equality-of-variances---homogeneity&#34; id=&#34;toc-equality-of-variances---homogeneity&#34;&gt;Equality of variances - homogeneity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#another-method-to-test-normality-and-homogeneity&#34; id=&#34;toc-another-method-to-test-normality-and-homogeneity&#34;&gt;Another method to test normality and homogeneity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#outliers&#34; id=&#34;toc-outliers&#34;&gt;Outliers&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#anova&#34; id=&#34;toc-anova&#34;&gt;ANOVA&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#preliminary-analyses&#34; id=&#34;toc-preliminary-analyses&#34;&gt;Preliminary analyses&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#anova-in-r&#34; id=&#34;toc-anova-in-r&#34;&gt;ANOVA in R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#interpretations-of-anova-results&#34; id=&#34;toc-interpretations-of-anova-results&#34;&gt;Interpretations of ANOVA results&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#whats-next&#34; id=&#34;toc-whats-next&#34;&gt;What’s next?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#post-hoc-test&#34; id=&#34;toc-post-hoc-test&#34;&gt;Post-hoc test&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#issue-of-multiple-testing&#34; id=&#34;toc-issue-of-multiple-testing&#34;&gt;Issue of multiple testing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#post-hoc-tests-in-r-and-their-interpretation&#34; id=&#34;toc-post-hoc-tests-in-r-and-their-interpretation&#34;&gt;Post-hoc tests in R and their interpretation&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#tukey-hsd-test&#34; id=&#34;toc-tukey-hsd-test&#34;&gt;Tukey HSD test&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#dunnetts-test&#34; id=&#34;toc-dunnetts-test&#34;&gt;Dunnett’s test&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#other-p-values-adjustment-methods&#34; id=&#34;toc-other-p-values-adjustment-methods&#34;&gt;Other &lt;em&gt;p&lt;/em&gt;-values adjustment methods&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#visualization-of-anova-and-post-hoc-tests-on-the-same-plot&#34; id=&#34;toc-visualization-of-anova-and-post-hoc-tests-on-the-same-plot&#34;&gt;Visualization of ANOVA and post-hoc tests on the same plot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#summary&#34; id=&#34;toc-summary&#34;&gt;Summary&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/anova-in-r.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;ANOVA (ANalysis Of VAriance) is a &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical test&lt;/a&gt; to determine whether two or more population means are different. In other words, it is used to &lt;strong&gt;compare two or more groups&lt;/strong&gt; to see if they are significantly &lt;strong&gt;different&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In practice, however, the:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;&lt;strong&gt;Student t-test&lt;/strong&gt;&lt;/a&gt; is used to compare &lt;strong&gt;2 groups&lt;/strong&gt;;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;ANOVA&lt;/strong&gt; generalizes the t-test beyond 2 groups, so it is used to compare &lt;strong&gt;3 or more groups&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that there are several versions of the ANOVA (e.g., one-way ANOVA, &lt;a href=&#34;https://statsandr.com/blog/two-way-anova-in-r/&#34;&gt;two-way ANOVA&lt;/a&gt;, mixed ANOVA, repeated measures ANOVA, etc.). In this article, we present the simplest form only—the &lt;strong&gt;one-way ANOVA&lt;/strong&gt;&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;—and we refer to it as ANOVA in the remaining of the article.&lt;/p&gt;
&lt;p&gt;Although ANOVA is used to make inference about &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#mean&#34;&gt;means&lt;/a&gt; of different groups, the method is called “analysis of &lt;em&gt;&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#variance&#34;&gt;variance&lt;/a&gt;&lt;/em&gt;”. It is called like this because it compares the “between” variance (the variance between the different groups) and the variance “within” (the variance within each group). If the between variance is significantly larger than the within variance, the group means are declared to be different. Otherwise, we cannot conclude one way or the other. The two variances are compared to each other by taking the ratio (&lt;span class=&#34;math inline&#34;&gt;\(\frac{variance_{between}}{variance_{within}}\)&lt;/span&gt;) and then by comparing this ratio to a threshold from the Fisher &lt;a href=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/&#34;&gt;probability distribution&lt;/a&gt; (a threshold based on a specific significance level, usually 5%).&lt;/p&gt;
&lt;p&gt;This is enough theory regarding the ANOVA method for now. In the remaining of this article, we discuss about it from a more practical point of view, and in particular we will cover the following points:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the aim of the ANOVA, when it should be used and the null/alternative hypothesis&lt;/li&gt;
&lt;li&gt;the underlying assumptions of the ANOVA and how to check them&lt;/li&gt;
&lt;li&gt;how to perform the ANOVA in R&lt;/li&gt;
&lt;li&gt;how to interpret results of the ANOVA&lt;/li&gt;
&lt;li&gt;understand the notion of post-hoc test and interpret the results&lt;/li&gt;
&lt;li&gt;how to visualize results of ANOVA and post-hoc tests&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;data&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Data&lt;/h1&gt;
&lt;p&gt;Data for the present article is the &lt;code&gt;penguins&lt;/code&gt; dataset (an alternative to the well-known &lt;code&gt;iris&lt;/code&gt; dataset), accessible via the &lt;a href=&#34;https://github.com/allisonhorst/palmerpenguins&#34; target=&#34;_blank&#34;&gt;&lt;code&gt;{palmerpenguins}&lt;/code&gt; package&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# install.packages(&amp;quot;palmerpenguins&amp;quot;)
library(palmerpenguins)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The dataset contains data for 344 penguins of 3 different species (Adelie, Chinstrap and Gentoo). The dataset contains 8 variables, but we focus only on the flipper length and the species for this article, so we keep only those 2 variables:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(tidyverse)

dat &amp;lt;- penguins %&amp;gt;%
  select(species, flipper_length_mm)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;(If you are unfamiliar with the pipe operator (&lt;code&gt;%&amp;gt;%&lt;/code&gt;), you can also &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/#subset-a-data-frame&#34;&gt;select variables&lt;/a&gt; with &lt;code&gt;penguins[, c(&#34;species&#34;, &#34;flipper_length_mm&#34;)]&lt;/code&gt;. Learn more ways to select variables in the article about &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/&#34;&gt;data manipulation&lt;/a&gt;.)&lt;/p&gt;
&lt;p&gt;Below some basic &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt; and a plot (made with the &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;&lt;code&gt;{ggplot2}&lt;/code&gt; package&lt;/a&gt;) of our dataset before we proceed to the goal of the ANOVA:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       species    flipper_length_mm
##  Adelie   :152   Min.   :172.0    
##  Chinstrap: 68   1st Qu.:190.0    
##  Gentoo   :124   Median :197.0    
##                  Mean   :200.9    
##                  3rd Qu.:213.0    
##                  Max.   :231.0    
##                  NA&amp;#39;s   :2&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Flipper length varies from 172 to 231 mm, with a mean of 200.9 mm. There are respectively 152, 68 and 124 penguins of the species Adelie, Chinstrap and Gentoo.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggplot2)

ggplot(dat) +
  aes(x = species, y = flipper_length_mm, color = species) +
  geom_jitter() +
  theme(legend.position = &amp;quot;none&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/figure-html/unnamed-chunk-4-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Here, the &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#factor&#34;&gt;factor&lt;/a&gt; is the &lt;code&gt;species&lt;/code&gt; variable which contains 3 modalities or groups (Adelie, Chinstrap and Gentoo).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;aim-and-hypotheses-of-anova&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Aim and hypotheses of ANOVA&lt;/h1&gt;
&lt;p&gt;As mentioned in the introduction, the ANOVA is used to compare groups (in practice, 3 or more groups). More generally, it is used to:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;study whether measurements are similar across different modalities (also called levels or treatments in the context of ANOVA) of a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;categorical&lt;/a&gt; variable&lt;/li&gt;
&lt;li&gt;compare the impact of the different levels of a categorical variable on a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#quantitative&#34;&gt;quantitative&lt;/a&gt; variable&lt;/li&gt;
&lt;li&gt;explain a quantitative variable based on a qualitative variable&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In this context and as an example, we are going to use an ANOVA to help us answer the question: “&lt;strong&gt;Is the length of the flippers different between the 3 species of penguins?&lt;/strong&gt;”.&lt;/p&gt;
&lt;p&gt;The null and alternative hypothesis of an ANOVA are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu_{Adelie} = \mu_{Chinstrap} = \mu_{Gentoo}\)&lt;/span&gt; (&lt;span class=&#34;math inline&#34;&gt;\(\Rightarrow\)&lt;/span&gt; the 3 species are equal in terms of flipper length)&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: &lt;em&gt;at least&lt;/em&gt; one mean is different (&lt;span class=&#34;math inline&#34;&gt;\(\Rightarrow\)&lt;/span&gt; at least one species is different from the other 2 species in terms of flipper length)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Be careful that the alternative hypothesis is &lt;strong&gt;&lt;em&gt;not&lt;/em&gt;&lt;/strong&gt; that all means are different. The opposite of all means being equal (&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;) is that &lt;em&gt;at least&lt;/em&gt; one mean is different from the others (&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;).&lt;/p&gt;
&lt;p&gt;In this sense, if the null hypothesis is rejected, it means that at least one species is different from the other 2, but not necessarily that all 3 species are different from each other. It could be that flipper length for the species Gentoo is different than for the species Chinstrap and Adelie, but flipper length is similar between Chinstrap and Adelie. Other types of test (known as post-hoc tests and covered in this &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#post-hoc-test&#34;&gt;section&lt;/a&gt;) must be performed to test whether all 3 species differ.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;underlying-assumptions-of-anova&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Underlying assumptions of ANOVA&lt;/h1&gt;
&lt;p&gt;As for many &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt;, there are some assumptions that need to be met in order to be able to interpret the results. When one or several assumptions are not met, although it is technically possible to perform these tests, it would be incorrect to interpret the results and trust the conclusions.&lt;/p&gt;
&lt;p&gt;Below are the assumptions of the ANOVA, how to test them and which other tests exist if an assumption is not met:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Variable type&lt;/strong&gt;: ANOVA requires a mix of one &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#continuous&#34;&gt;continuous quantitative&lt;/a&gt; dependent variable (which corresponds to the measurements to which the question relates) and one &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;qualitative&lt;/a&gt; independent variable (with at least 2 levels which will determine the groups to compare).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Independence&lt;/strong&gt;: the data, collected from a representative and randomly selected portion of the total &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;population&lt;/a&gt;, should be independent between groups and within each group. The assumption of independence is most often verified based on the design of the experiment and on the good control of experimental conditions rather than via a formal test. If you are still unsure about independence based on the experiment design, ask yourself if one observation is related to another (if one observation has an impact on another) within each group or between the groups themselves. If not, it is most likely that you have independent &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;samples&lt;/a&gt;. If observations between samples (forming the different groups to be compared) are dependent (for example, if three measurements have been collected on the &lt;strong&gt;same individuals&lt;/strong&gt; as it is often the case in medical studies when measuring a metric (i) before, (ii) during and (iii) after a treatment), the repeated measures ANOVA should be preferred in order to take into account the dependency between the samples.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Normality&lt;/strong&gt;:
&lt;ul&gt;
&lt;li&gt;In case of small samples, residuals&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt; should follow approximately a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;&lt;strong&gt;normal distribution&lt;/strong&gt;&lt;/a&gt;. The normality assumption can be tested visually thanks to a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt; and a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#qq-plot&#34;&gt;QQ-plot&lt;/a&gt;, and/or formally via a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#normality-test&#34;&gt;normality test&lt;/a&gt; such as the Shapiro-Wilk or Kolmogorov-Smirnov test. If, even after a transformation of your data (e.g., logarithmic transformation, square root, Box-Cox, etc.), the residuals still do not follow approximately a normal distribution, the &lt;a href=&#34;https://statsandr.com/blog/kruskal-wallis-test-nonparametric-version-anova/&#34;&gt;Kruskal-Wallis test&lt;/a&gt; can be applied (&lt;code&gt;kruskal.test(variable ~ group, data = dat&lt;/code&gt; in R). This non-parametric test, robust to non normal distributions, has the same goal than the ANOVA—compare 3 or more groups—but it uses sample medians instead of sample means to compare groups.&lt;/li&gt;
&lt;li&gt;In case of large samples, &lt;strong&gt;normality is not required&lt;/strong&gt; (this is a common misconception!). By the &lt;a href=&#34;https://en.wikipedia.org/wiki/Central_limit_theorem&#34; target=&#34;_blank&#34;&gt;central limit theorem&lt;/a&gt;, sample means of large samples are often well-approximated by a normal distribution even if the data are not normally distributed &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-stevens2013intermediate&#34;&gt;Stevens 2013&lt;/a&gt;)&lt;/span&gt;.&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt; It is therefore not required to test the normality assumption when the number of observations in each group/sample is large (usually &lt;span class=&#34;math inline&#34;&gt;\(n \ge 30\)&lt;/span&gt;).&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Equality of variances&lt;/strong&gt;: the variances of the different groups should be equal in the populations (an assumption called homogeneity of the variances, or even sometimes referred as homoscedasticity, as opposed to heteroscedasticity if variances are different across groups). This assumption can be tested graphically (by comparing the dispersion in a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#boxplot&#34;&gt;boxplot&lt;/a&gt; or &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#dotplot&#34;&gt;dotplot&lt;/a&gt; for instance), or more formally via the Levene’s test (&lt;code&gt;leveneTest(variable ~ group)&lt;/code&gt; from the &lt;code&gt;{car}&lt;/code&gt; package) or Bartlett’s test, among others. If the hypothesis of equal variances is rejected, another version of the ANOVA can be used: the Welch ANOVA (&lt;code&gt;oneway.test(variable ~ group, var.equal = FALSE)&lt;/code&gt;). Note that the Welch ANOVA does not require homogeneity of the variances, but the distributions should still follow approximately a normal distribution. Note that the &lt;a href=&#34;https://statsandr.com/blog/kruskal-wallis-test-nonparametric-version-anova/&#34;&gt;Kruskal-Wallis test&lt;/a&gt; does not require the assumptions of normality nor homoscedasticity of the variances.&lt;a href=&#34;#fn4&#34; class=&#34;footnote-ref&#34; id=&#34;fnref4&#34;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Outliers&lt;/strong&gt;: An &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outlier&lt;/a&gt; is a value or an observation that is distant from the other observations. There should be &lt;strong&gt;no significant outliers in the different groups&lt;/strong&gt;, or the conclusions of your ANOVA may be flawed. There are several methods to &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;detect outliers&lt;/a&gt; in your data but in order to deal with them, it is your choice to either:
&lt;ul&gt;
&lt;li&gt;use the non-parametric version (i.e., the Kruskal-Wallis test)&lt;/li&gt;
&lt;li&gt;transform your data (logarithmic or Box-Cox transformation, among others)&lt;/li&gt;
&lt;li&gt;or remove them (be careful)&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Choosing the appropriate test depending on whether assumptions are met may be confusing so here is a brief summary:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Check that your observations are independent.&lt;/li&gt;
&lt;li&gt;Sample sizes:
&lt;ul&gt;
&lt;li&gt;In case of small samples, test the normality of residuals:
&lt;ul&gt;
&lt;li&gt;If normality is assumed, test the homogeneity of the variances:
&lt;ul&gt;
&lt;li&gt;If variances are equal, use &lt;strong&gt;ANOVA&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;If variances are not equal, use the &lt;strong&gt;Welch ANOVA&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;If normality is not assumed, use the &lt;strong&gt;Kruskal-Wallis test&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;In case of large samples normality is assumed, so test the homogeneity of the variances:
&lt;ul&gt;
&lt;li&gt;If variances are equal, use &lt;strong&gt;ANOVA&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;If variances are not equal, use the &lt;strong&gt;Welch ANOVA&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Now that we have seen the underlying assumptions of the ANOVA, we review them specifically for our dataset before applying the appropriate version of the test.&lt;/p&gt;
&lt;div id=&#34;variable-type&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Variable type&lt;/h2&gt;
&lt;p&gt;The dependent variable &lt;code&gt;flipper_length_mm&lt;/code&gt; is a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#quantitative&#34;&gt;quantitative&lt;/a&gt; variable and the independent variable &lt;code&gt;species&lt;/code&gt; is a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;qualitative&lt;/a&gt; one (with 3 levels corresponding to the 3 species). So we have a mix of the two types of variable and this assumption is met.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;independence&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Independence&lt;/h2&gt;
&lt;p&gt;Independence of the observations is assumed as data have been collected from a randomly selected portion of the population and measurements within and between the 3 samples are not related.&lt;/p&gt;
&lt;p&gt;The independence assumption is most often verified based on the design of the experiment and on the good control of experimental conditions, as it is the case here.&lt;/p&gt;
&lt;p&gt;If you really want to test it more formally, you can, however, test it via a statistical test—the Durbin-Watson test (in R: &lt;code&gt;durbinWatsonTest(res_lm)&lt;/code&gt; where &lt;code&gt;res_lm&lt;/code&gt; is a linear model). The null hypothesis of this test specifies an autocorrelation coefficient = 0, while the alternative hypothesis specifies an autocorrelation coefficient &lt;span class=&#34;math inline&#34;&gt;\(\ne\)&lt;/span&gt; 0.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;normality&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Normality&lt;/h2&gt;
&lt;p&gt;Since the smallest sample size per group (i.e., per species) is 68, we have large samples. Therefore, we do not need to check normality.&lt;/p&gt;
&lt;p&gt;Usually, we would directly test the homogeneity of the variances without testing normality. However, for the sake of illustration, we act as if the sample sizes were small in order to illustrate what would need to be done in that case.&lt;/p&gt;
&lt;p&gt;Remember that &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normality&lt;/a&gt; of residuals can be tested visually via a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt; and a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#qq-plot&#34;&gt;QQ-plot&lt;/a&gt;, and/or formally via a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#normality-test&#34;&gt;normality test&lt;/a&gt; (Shapiro-Wilk test for instance).&lt;/p&gt;
&lt;p&gt;Before checking the normality assumption, we first need to compute the ANOVA (more on that in this &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#anova-in-r&#34;&gt;section&lt;/a&gt;). We then save the results in &lt;code&gt;res_aov&lt;/code&gt; :&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;res_aov &amp;lt;- aov(flipper_length_mm ~ species,
  data = dat
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can now check normality visually:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;par(mfrow = c(1, 2)) # combine plots

# histogram
hist(res_aov$residuals)

# QQ-plot
library(car)
qqPlot(res_aov$residuals,
  id = FALSE # id = FALSE to remove point identification
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/figure-html/unnamed-chunk-6-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;From the histogram and QQ-plot above, we can already see that the normality assumption seems to be met. Indeed, the histogram roughly form a bell curve, indicating that the residuals follow a normal distribution. Furthermore, points in the QQ-plots roughly follow the straight line and most of them are within the confidence bands, also indicating that residuals follow approximately a normal distribution.&lt;/p&gt;
&lt;p&gt;Some researchers stop here and assume that normality is met, while others also test the assumption via a formal &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#normality-test&#34;&gt;normality test&lt;/a&gt;. It is your choice to test it (i) only visually, (ii) only via a normality test, or (iii) both visually AND via a normality test. Bear in mind, however, the two following points:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;ANOVA is quite robust to small deviations from normality. This means that it is not an issue (from the perspective of the interpretation of the ANOVA results) if a small number of points deviates slightly from the normality,&lt;/li&gt;
&lt;li&gt;normality tests are sometimes quite conservative, meaning that the null hypothesis of normality may be rejected due to a limited deviation from normality. This is especially the case with large samples as power of the test increases with the sample size.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In practice, I tend to prefer the (i) visual approach only, but again, this is a matter of personal choice and also depends on the context of the analysis.&lt;/p&gt;
&lt;p&gt;Still for the sake of illustration, we also now test the normality assumption via a normality test. You can use the Shapiro-Wilk test or the Kolmogorov-Smirnov test, among others.&lt;/p&gt;
&lt;p&gt;Remember that the null and alternative hypothesis of these tests are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: data come from a normal distribution&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: data do &lt;strong&gt;&lt;em&gt;not&lt;/em&gt;&lt;/strong&gt; come from a normal distribution&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In R, we can test normality of the residuals with the Shapiro-Wilk test thanks to the &lt;code&gt;shapiro.test()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;shapiro.test(res_aov$residuals)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Shapiro-Wilk normality test
## 
## data:  res_aov$residuals
## W = 0.99452, p-value = 0.2609&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;P&lt;/em&gt;-value of the Shapiro-Wilk test on the residuals is larger than the usual significance level of &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 5\%\)&lt;/span&gt;, so we do not reject the hypothesis that residuals follow a normal distribution (&lt;em&gt;p&lt;/em&gt;-value = 0.261).&lt;/p&gt;
&lt;p&gt;This result is in line with the visual approach. In our case, the normality assumption is thus met both visually and formally.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Side note: Remind that the p-value is the &lt;a href=&#34;https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/&#34;&gt;probability&lt;/a&gt; of having observations as extreme as the ones we have observed in the sample(s) given that the null hypothesis is true. If the p-value &lt;span class=&#34;math inline&#34;&gt;\(&amp;lt; \alpha\)&lt;/span&gt; (indicating that it is not likely to observe the data we have in the sample given that the null hypothesis is true), the null hypothesis is rejected, otherwise the null hypothesis is not rejected. See more about &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/#a-note-on-p-value-and-significance-level-alpha&#34;&gt;p-value and significance level&lt;/a&gt; if you are unfamiliar with those important statistical concepts.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Remember that if the normality assumption was not reached, some transformation(s) would need to be applied on the raw data in the hope that residuals would better fit a normal distribution, or you would need to use the non-parametric version of the ANOVA—the &lt;a href=&#34;https://statsandr.com/blog/kruskal-wallis-test-nonparametric-version-anova/&#34;&gt;Kruskal-Wallis test&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;As pointed out by a reader (see comments at the very end of the article), the normality assumption can also be tested on the “raw” data (i.e., the observations) instead of the residuals. However, if you test the normality assumption on the raw data, it must be tested for &lt;em&gt;each group separately&lt;/em&gt; as the ANOVA requires normality in &lt;em&gt;each group&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Testing normality on all residuals or on the observations per group is equivalent, and will give similar results. Indeed, saying “The distribution of Y within each group is normally distributed” is the same as saying “The residuals are normally distributed”.&lt;/p&gt;
&lt;p&gt;Remember that residuals are the distance between the actual value of Y and the mean value of Y for a specific value of X, so the grouping variable is induced in the computation of the residuals.&lt;/p&gt;
&lt;p&gt;So in summary, in ANOVA you actually have two options for testing normality:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Checking normality separately for each group on the “raw” data (Y values)&lt;/li&gt;
&lt;li&gt;Checking normality on all residuals (but not per group)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In practice, you will see that it is often easier to just use the residuals and check them all together, especially if you have many groups or few observations per group.&lt;/p&gt;
&lt;p&gt;If you are still not convinced: remember that an ANOVA is a special case of a linear model. Suppose your independent variable is a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#continuous&#34;&gt;continuous variable&lt;/a&gt; (instead of a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;categorical variable&lt;/a&gt;), the only option you have left is to check normality on the residuals, which is precisely what is done for testing normality in &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;linear regression&lt;/a&gt; models.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;equality-of-variances---homogeneity&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Equality of variances - homogeneity&lt;/h2&gt;
&lt;p&gt;Assuming residuals follow a normal distribution, it is now time to check whether the variances are equal across species or not. The result will have an impact on whether we use the ANOVA or the Welch ANOVA.&lt;/p&gt;
&lt;p&gt;This can again be verified visually—via a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#boxplot&#34;&gt;boxplot&lt;/a&gt; or &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#dotplot&#34;&gt;dotplot&lt;/a&gt;—or more formally via a statistical test (Levene’s test, among others).&lt;/p&gt;
&lt;p&gt;Visually, we have:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Boxplot
boxplot(flipper_length_mm ~ species,
  data = dat
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/figure-html/unnamed-chunk-8-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Dotplot
library(&amp;quot;lattice&amp;quot;)

dotplot(flipper_length_mm ~ species,
  data = dat
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/figure-html/unnamed-chunk-8-2.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Both the boxplot and the dotplot show a similar variance for the different species. In the boxplot, this can be seen by the fact that the boxes and the whiskers have a comparable size for all species.&lt;/p&gt;
&lt;p&gt;There are a couple of &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt; as shown by the points outside the whiskers, but this does not change the fact that the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#dispersion&#34;&gt;dispersion&lt;/a&gt; is more or less the same between the different species.&lt;/p&gt;
&lt;p&gt;In the dotplot, this can be seen by the fact that points for all 3 species have more or less the same &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#range&#34;&gt;range&lt;/a&gt;, a sign of the dispersion and thus the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#variance&#34;&gt;variance&lt;/a&gt; being similar.&lt;/p&gt;
&lt;p&gt;Like the normality assumption, if you feel that the visual approach is not sufficient, you can formally test for equality of the variances with a Levene’s or Bartlett’s test. Notice that the Levene’s test is less sensitive to departures from normal distribution than the Bartlett’s test.&lt;/p&gt;
&lt;p&gt;The null and alternative hypothesis for both tests are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: variances are equal&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: at least one variance is different&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In R, the Levene’s test can be performed thanks to the &lt;code&gt;leveneTest()&lt;/code&gt; function from the &lt;code&gt;{car}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Levene&amp;#39;s test
library(car)

leveneTest(flipper_length_mm ~ species,
  data = dat
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Levene&amp;#39;s Test for Homogeneity of Variance (center = median)
##        Df F value Pr(&amp;gt;F)
## group   2  0.3306 0.7188
##       339&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value being larger than the significance level of 0.05, we do not reject the null hypothesis, so we cannot reject the hypothesis that variances are equal between species (&lt;em&gt;p&lt;/em&gt;-value = 0.719).&lt;/p&gt;
&lt;p&gt;This result is also in line with the visual approach, so the homogeneity of variances is met both visually and formally.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;another-method-to-test-normality-and-homogeneity&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Another method to test normality and homogeneity&lt;/h2&gt;
&lt;p&gt;For your information, it is also possible to test the homogeneity of the variances and the normality of the residuals visually (and both at the same time) via the &lt;code&gt;plot()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;par(mfrow = c(1, 2)) # combine plots

# 1. Homogeneity of variances
plot(res_aov, which = 3)

# 2. Normality
plot(res_aov, which = 2)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/figure-html/unnamed-chunk-10-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Plot on the left hand side shows that there is no evident relationships between residuals and fitted values (the mean of each group), so homogeneity of variances is assumed. If homogeneity of variances was violated, the red line would not be flat (horizontal).&lt;/p&gt;
&lt;p&gt;Plot on the right hand side shows that residuals follow approximately a normal distribution, so normality is assumed. If normality was violated, points would consistently deviate from the dashed line.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;outliers&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Outliers&lt;/h2&gt;
&lt;p&gt;There are several techniques to &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;detect outliers&lt;/a&gt;. In this article, we focus on the most simple one (yet very efficient)—the visual approach via a boxplot:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;boxplot(flipper_length_mm ~ species,
  data = dat
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/figure-html/unnamed-chunk-11-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;There is one outlier in the group &lt;code&gt;Adelie&lt;/code&gt;, as defined by the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#interquartile-range&#34;&gt;interquartile range&lt;/a&gt; criterion. This point is, however, not seen as a significant outlier so we can assume that the assumption of no significant outliers is met.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;anova&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;ANOVA&lt;/h1&gt;
&lt;p&gt;We showed that all assumptions of the ANOVA are met.&lt;/p&gt;
&lt;p&gt;We can thus proceed to the implementation of the ANOVA in R, but first, let’s do some preliminary analyses to better understand the research question.&lt;/p&gt;
&lt;div id=&#34;preliminary-analyses&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Preliminary analyses&lt;/h2&gt;
&lt;p&gt;A good practice before actually performing the ANOVA in R is to &lt;strong&gt;visualize the data&lt;/strong&gt; in relation to the research question. The best way to do so is to draw and compare boxplots of the quantitative variable &lt;code&gt;flipper_length_mm&lt;/code&gt; for each species.&lt;/p&gt;
&lt;p&gt;This can be done with the &lt;code&gt;boxplot()&lt;/code&gt; function in base R (same code than the visual check of equal variances):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;boxplot(flipper_length_mm ~ species,
  data = dat
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/figure-html/unnamed-chunk-12-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Or with the &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;&lt;code&gt;{ggplot2}&lt;/code&gt; package&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggplot2)

ggplot(dat) +
  aes(x = species, y = flipper_length_mm) +
  geom_boxplot()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/figure-html/unnamed-chunk-13-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The boxplots above show that, at least for our sample, penguins of the species &lt;code&gt;Gentoo&lt;/code&gt; seem to have the biggest flipper, and &lt;code&gt;Adelie&lt;/code&gt; species the smallest flipper.&lt;/p&gt;
&lt;p&gt;Besides a boxplot for each species, it is also a good practice to compute some &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;&lt;strong&gt;descriptive statistics&lt;/strong&gt;&lt;/a&gt; such as the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#mean&#34;&gt;mean&lt;/a&gt; and &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#standard-deviation-and-variance&#34;&gt;standard deviation&lt;/a&gt; by species.&lt;/p&gt;
&lt;p&gt;This can be done, for instance, with the &lt;code&gt;aggregate()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;aggregate(flipper_length_mm ~ species,
  data = dat,
  function(x) round(c(mean = mean(x), sd = sd(x)), 2)
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##     species flipper_length_mm.mean flipper_length_mm.sd
## 1    Adelie                 189.95                 6.54
## 2 Chinstrap                 195.82                 7.13
## 3    Gentoo                 217.19                 6.48&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or with the &lt;code&gt;summarise()&lt;/code&gt; and &lt;code&gt;group_by()&lt;/code&gt; functions from the &lt;code&gt;{dplyr}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(dplyr)

group_by(dat, species) %&amp;gt;%
  summarise(
    mean = mean(flipper_length_mm, na.rm = TRUE),
    sd = sd(flipper_length_mm, na.rm = TRUE)
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 3
##   species    mean    sd
##   &amp;lt;fct&amp;gt;     &amp;lt;dbl&amp;gt; &amp;lt;dbl&amp;gt;
## 1 Adelie     190.  6.54
## 2 Chinstrap  196.  7.13
## 3 Gentoo     217.  6.48&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mean is also the lowest for &lt;code&gt;Adelie&lt;/code&gt; and highest for &lt;code&gt;Gentoo&lt;/code&gt;. Boxplots and descriptive statistics are, however, not enough to conclude that flippers are significantly different in the 3 populations of penguins.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;anova-in-r&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;ANOVA in R&lt;/h2&gt;
&lt;p&gt;As you guessed by now, only the ANOVA can help us to make inference about the population given the sample at hand, and help us to answer the initial research question “Is the length of the flippers different between the 3 species of penguins?”.&lt;/p&gt;
&lt;p&gt;ANOVA in R can be done in several ways, of which two are presented below:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;With the &lt;code&gt;oneway.test()&lt;/code&gt; function:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# 1st method:
oneway.test(flipper_length_mm ~ species,
  data = dat,
  var.equal = TRUE # assuming equal variances
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	One-way analysis of means
## 
## data:  flipper_length_mm and species
## F = 594.8, num df = 2, denom df = 339, p-value &amp;lt; 2.2e-16&lt;/code&gt;&lt;/pre&gt;
&lt;ol start=&#34;2&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;With the &lt;code&gt;summary()&lt;/code&gt; and &lt;code&gt;aov()&lt;/code&gt; functions:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# 2nd method:
res_aov &amp;lt;- aov(flipper_length_mm ~ species,
  data = dat
)

summary(res_aov)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##              Df Sum Sq Mean Sq F value Pr(&amp;gt;F)    
## species       2  52473   26237   594.8 &amp;lt;2e-16 ***
## Residuals   339  14953      44                   
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## 2 observations deleted due to missingness&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see from the two outputs above, the test statistic (&lt;code&gt;F =&lt;/code&gt; in the first method and &lt;code&gt;F value&lt;/code&gt; in the second one) and the &lt;em&gt;p&lt;/em&gt;-value (&lt;code&gt;p-value&lt;/code&gt; in the first method and &lt;code&gt;Pr(&amp;gt;F)&lt;/code&gt; in the second one) are exactly the same for both methods, which means that in case of equal variances, results and conclusions will be unchanged.&lt;/p&gt;
&lt;p&gt;The advantage of the first method is that it is easy to switch from the ANOVA (used when variances are equal) to the Welch ANOVA (used when variances are &lt;strong&gt;un&lt;/strong&gt;equal). This can be done by replacing &lt;code&gt;var.equal = TRUE&lt;/code&gt; by &lt;code&gt;var.equal = FALSE&lt;/code&gt;, as presented below:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;oneway.test(flipper_length_mm ~ species,
  data = dat,
  var.equal = FALSE # assuming unequal variances
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	One-way analysis of means (not assuming equal variances)
## 
## data:  flipper_length_mm and species
## F = 614.01, num df = 2.00, denom df = 172.76, p-value &amp;lt; 2.2e-16&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The advantage of the second method, however, is that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the full ANOVA table (with degrees of freedom, mean squares, etc.) is printed, which may be of interest in some (theoritical) cases&lt;/li&gt;
&lt;li&gt;results of the ANOVA (&lt;code&gt;res_aov&lt;/code&gt;) can be saved for later use (especially useful for &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#post-hoc-test&#34;&gt;post-hoc tests&lt;/a&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;interpretations-of-anova-results&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Interpretations of ANOVA results&lt;/h2&gt;
&lt;p&gt;Given that the &lt;em&gt;p&lt;/em&gt;-value is smaller than 0.05, we reject the null hypothesis, so we reject the hypothesis that all means are equal. Therefore, we can conclude that &lt;strong&gt;at least one species is different than the others in terms of flippers length&lt;/strong&gt; (&lt;em&gt;p&lt;/em&gt;-value &amp;lt; 2.2e-16).&lt;/p&gt;
&lt;p&gt;(&lt;em&gt;For the sake of illustration&lt;/em&gt;, if the &lt;em&gt;p&lt;/em&gt;-value was larger than 0.05: we cannot reject the null hypothesis that all means are equal, so we cannot reject the hypothesis that the 3 considered species of penguins are equal in terms of flippers length.)&lt;/p&gt;
&lt;p&gt;A nice and easy way to report results of an ANOVA in R is with the &lt;code&gt;report()&lt;/code&gt; function from the &lt;code&gt;{report}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# install.packages(&amp;quot;remotes&amp;quot;)
# remotes::install_github(&amp;quot;easystats/report&amp;quot;) # You only need to do that once
library(&amp;quot;report&amp;quot;) # Load the package every time you start R

report(res_aov)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## The ANOVA (formula: flipper_length_mm ~ species) suggests that:
## 
##   - The main effect of species is statistically significant and large (F(2, 339)
## = 594.80, p &amp;lt; .001; Eta2 = 0.78, 95% CI [0.75, 1.00])
## 
## Effect sizes were labelled following Field&amp;#39;s (2013) recommendations.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, the function interprets the results for you and indicates a large and significant main effect of the species on the flipper length (&lt;em&gt;p&lt;/em&gt;-value &amp;lt; .001).&lt;/p&gt;
&lt;p&gt;Note that the &lt;code&gt;report()&lt;/code&gt; function can be used for other analyses. See more &lt;a href=&#34;https://statsandr.com/blog/tips-and-tricks-in-rstudio-and-r-markdown/&#34;&gt;tips and tricks in R&lt;/a&gt; if you find this one useful.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;whats-next&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;What’s next?&lt;/h2&gt;
&lt;p&gt;If the &lt;strong&gt;null hypothesis is not rejected&lt;/strong&gt; (&lt;em&gt;p&lt;/em&gt;-value &lt;span class=&#34;math inline&#34;&gt;\(\ge\)&lt;/span&gt; 0.05), it means that we do not reject the hypothesis that all groups are equal. The ANOVA more or less stops here.&lt;/p&gt;
&lt;p&gt;Other types of analyses can be performed of course, but—given the data at hand—we could not prove that at least one group was different so we usually do not go further with the ANOVA.&lt;/p&gt;
&lt;p&gt;On the contrary, if the &lt;strong&gt;null hypothesis is rejected&lt;/strong&gt; (as it is our case since the &lt;em&gt;p&lt;/em&gt;-value &amp;lt; 0.05), we proved that at least one group is different. We can decide to stop here if we are only interested to test whether all species are equal in terms of flippers length.&lt;/p&gt;
&lt;p&gt;But most of the time, when we showed thanks to an ANOVA that at least one group is different, we are also interested in knowing &lt;strong&gt;which&lt;/strong&gt; one(s) is(are) different. Results of an ANOVA, however, do &lt;strong&gt;&lt;em&gt;NOT&lt;/em&gt;&lt;/strong&gt; tell us which group(s) is(are) different from the others.&lt;/p&gt;
&lt;p&gt;To test this, we need to use other types of test, referred as post-hoc tests (in Latin, “after this”, so after obtaining statistically significant ANOVA results) or multiple pairwise-comparison tests.&lt;a href=&#34;#fn5&#34; class=&#34;footnote-ref&#34; id=&#34;fnref5&#34;&gt;&lt;sup&gt;5&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;This family of statistical tests is the topic of the following sections.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;post-hoc-test&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Post-hoc test&lt;/h1&gt;
&lt;div id=&#34;issue-of-multiple-testing&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Issue of multiple testing&lt;/h2&gt;
&lt;p&gt;In order to see which group(s) is(are) different from the others, we need to &lt;strong&gt;compare groups 2 by 2&lt;/strong&gt;. In practice, since there are 3 species, we are going to compare species 2 by 2 as follows:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Chinstrap versus Adelie&lt;/li&gt;
&lt;li&gt;Gentoo vs. Adelie&lt;/li&gt;
&lt;li&gt;Gentoo vs. Chinstrap&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In theory, we could compare species thanks to 3 &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-tests&lt;/a&gt; since we need to compare 2 groups and a t-test is used precisely in that case.&lt;/p&gt;
&lt;p&gt;However, if several t-tests are performed, the issue of &lt;strong&gt;multiple testing&lt;/strong&gt; (also referred as multiplicity) arises. In short, when several &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt; are performed, some will have &lt;em&gt;p&lt;/em&gt;-values less than &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; purely by chance, even if all null hypotheses are in fact true.&lt;/p&gt;
&lt;p&gt;To demonstrate the problem, consider our case where we have 3 hypotheses to test and a desired significance level of 0.05.&lt;/p&gt;
&lt;p&gt;The probability of observing at least one significant result (at least one &lt;em&gt;p&lt;/em&gt;-value &amp;lt; 0.05) just due to chance is:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{equation}
\begin{split}
P(\text{at least 1 sig. result}) &amp;amp; = 1 - P(\text{no sig. results}) \\
&amp;amp; = 1 - (1 - 0.05)^3 \\
&amp;amp; = 0.142625
\end{split}
\end{equation}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;So, with as few as 3 tests being considered, we already have a 14.26% chance of observing at least one significant result, even if all of the tests are actually not significant.&lt;/p&gt;
&lt;p&gt;And as the number of groups increases, the number of comparisons increases as well, so the probability of having a significant result simply due to chance keeps increasing.&lt;/p&gt;
&lt;p&gt;For example, with 10 groups we need to make 45 comparisons and the probability of having at least one significant result by chance becomes &lt;span class=&#34;math inline&#34;&gt;\(1 - (1 - 0.05)^{45} = 90\%\)&lt;/span&gt;. So it is very likely to observe a significant result just by chance when comparing 10 groups, and when we have 14 groups or more we are almost certain (99%) to have a false positive!&lt;/p&gt;
&lt;p&gt;Post-hoc tests take into account that multiple tests are done and deal with the problem by adjusting &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; in some way, so that the probability of observing at least one significant result due to chance remains below our desired significance level.&lt;a href=&#34;#fn6&#34; class=&#34;footnote-ref&#34; id=&#34;fnref6&#34;&gt;&lt;sup&gt;6&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;post-hoc-tests-in-r-and-their-interpretation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Post-hoc tests in R and their interpretation&lt;/h2&gt;
&lt;p&gt;Post-hoc tests are a family of statistical tests so there are several of them. The most common ones are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Tukey HSD&lt;/strong&gt;, used to compare &lt;strong&gt;all groups&lt;/strong&gt; to each other (so all possible comparisons of 2 groups).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dunnett&lt;/strong&gt;, used to make comparisons with a &lt;strong&gt;reference group&lt;/strong&gt;. For example, consider 2 treatment groups and one control group. If you only want to compare the 2 treatment groups with respect to the control group, and you do not want to compare the 2 treatment groups to each other, the Dunnett’s test is preferred.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Bonferroni correction&lt;/strong&gt; if one has a set of planned comparisons to do.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The Bonferroni correction is simple: you simply divide the desired global &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; level by the number of comparisons.&lt;/p&gt;
&lt;p&gt;In our example, we have 3 comparisons so if we want to keep a global &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;, we have &lt;span class=&#34;math inline&#34;&gt;\(\alpha&amp;#39; = \frac{0.05}{3} = 0.0167\)&lt;/span&gt;. We can then simply perform a Student’s t-test for each comparison, and compare the obtained &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values with this new &lt;span class=&#34;math inline&#34;&gt;\(\alpha&amp;#39;\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;The other two post-hoc tests are presented in the next sections.&lt;/p&gt;
&lt;p&gt;Note that variances are assumed to be equal for all three methods (unless you use the Welch’s t-test instead of the Student’s t-test with the Bonferroni correction). If variances are not equal, you can use the Games-Howell test, among others.&lt;/p&gt;
&lt;div id=&#34;tukey-hsd-test&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Tukey HSD test&lt;/h3&gt;
&lt;p&gt;In our case, since there is no “reference” species and we are interested in comparing all species, we are going to use the Tukey HSD test.&lt;/p&gt;
&lt;p&gt;In R, the Tukey HSD test is done as follows. This is where the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#anova-in-r&#34;&gt;second method&lt;/a&gt; to perform the ANOVA comes handy because the results (&lt;code&gt;res_aov&lt;/code&gt;) are reused for the post-hoc test:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(multcomp)

# Tukey HSD test:
post_test &amp;lt;- glht(res_aov,
  linfct = mcp(species = &amp;quot;Tukey&amp;quot;)
)

summary(post_test)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	 Simultaneous Tests for General Linear Hypotheses
## 
## Multiple Comparisons of Means: Tukey Contrasts
## 
## 
## Fit: aov(formula = flipper_length_mm ~ species, data = dat)
## 
## Linear Hypotheses:
##                         Estimate Std. Error t value Pr(&amp;gt;|t|)    
## Chinstrap - Adelie == 0   5.8699     0.9699   6.052 1.03e-08 ***
## Gentoo - Adelie == 0     27.2333     0.8067  33.760  &amp;lt; 1e-08 ***
## Gentoo - Chinstrap == 0  21.3635     1.0036  21.286  &amp;lt; 1e-08 ***
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## (Adjusted p values reported -- single-step method)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the output of the Tukey HSD test, we are interested in the table displayed after &lt;code&gt;Linear Hypotheses:&lt;/code&gt;, and more precisely, in the first and last column of the table. The first column shows the comparisons which have been made; the last column (&lt;code&gt;Pr(&amp;gt;|t|)&lt;/code&gt;) shows the adjusted&lt;a href=&#34;#fn7&#34; class=&#34;footnote-ref&#34; id=&#34;fnref7&#34;&gt;&lt;sup&gt;7&lt;/sup&gt;&lt;/a&gt; &lt;em&gt;p&lt;/em&gt;-values for each comparison (with the null hypothesis being the two groups are equal and the alternative hypothesis being the two groups are different).&lt;/p&gt;
&lt;p&gt;It is these adjusted &lt;em&gt;p&lt;/em&gt;-values that are used to test whether two groups are significantly different or not, and we can be confident that the entire set of comparisons collectively has an error rate of 0.05.&lt;/p&gt;
&lt;p&gt;In our example, we tested:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Chinstrap versus Adelie (line &lt;code&gt;Chinstrap - Adelie == 0&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;Gentoo vs. Adelie (line &lt;code&gt;Gentoo - Adelie == 0&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;Gentoo vs. Chinstrap (line &lt;code&gt;Gentoo - Chinstrap == 0&lt;/code&gt;)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;All three ajusted &lt;em&gt;p&lt;/em&gt;-values are smaller than 0.05, so we reject the null hypothesis for all comparisons, which means that &lt;strong&gt;all species are significantly different&lt;/strong&gt; in terms of flippers length.&lt;/p&gt;
&lt;p&gt;The results of the post-hoc test can be visualized with the &lt;code&gt;plot()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;par(mar = c(3, 8, 3, 3))
plot(post_test)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/figure-html/unnamed-chunk-21-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;We see that the confidence intervals do not cross the zero line, which indicate that all groups are significantly different.&lt;/p&gt;
&lt;p&gt;Note that the Tukey HSD test can also be done in R with the &lt;code&gt;TukeyHSD()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;TukeyHSD(res_aov)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   Tukey multiple comparisons of means
##     95% family-wise confidence level
## 
## Fit: aov(formula = flipper_length_mm ~ species, data = dat)
## 
## $species
##                       diff       lwr       upr p adj
## Chinstrap-Adelie  5.869887  3.586583  8.153191     0
## Gentoo-Adelie    27.233349 25.334376 29.132323     0
## Gentoo-Chinstrap 21.363462 19.000841 23.726084     0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With this code, it is the column &lt;code&gt;p adj&lt;/code&gt; (also the last column) which is of interest. Notice that the conclusions are the same than above: all species are significantly different in terms of flippers length.&lt;/p&gt;
&lt;p&gt;The results can also be visualized with the &lt;code&gt;plot()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(TukeyHSD(res_aov))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/figure-html/unnamed-chunk-23-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;dunnetts-test&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Dunnett’s test&lt;/h3&gt;
&lt;p&gt;We have seen in this &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#issue-of-multiple-testing&#34;&gt;section&lt;/a&gt; that as the number of groups increases, the number of comparisons also increases. And as the number of &lt;strong&gt;comparisons increases&lt;/strong&gt;, the post-hoc analysis must lower the individual significance level even further, which leads to &lt;strong&gt;lower statistical power&lt;/strong&gt; (so a difference between group means in the population is less likely to be detected).&lt;/p&gt;
&lt;p&gt;One method to mitigate this and increase the statistical power is by reducing the number of comparisons. This reduction allows the post-hoc procedure to use a larger individual error rate to achieve the desired global error rate.&lt;/p&gt;
&lt;p&gt;While comparing all possible groups with a Tukey HSD test is a common approach, many studies have a control group and several treatment groups. For these studies, you may need to compare the treatment groups only to the control group, which reduces the number of comparisons.&lt;/p&gt;
&lt;p&gt;Dunnett’s test does precisely this—it only compares a group taken as reference to all other groups, but it does not compare all groups to each others.&lt;/p&gt;
&lt;p&gt;So to recap:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the Tukey HSD test allows to compares &lt;strong&gt;all&lt;/strong&gt; groups but at the cost of &lt;strong&gt;less power&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;the Dunnett’s test allows to only make &lt;strong&gt;comparisons with a reference group&lt;/strong&gt;, but with the benefit of &lt;strong&gt;more power&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Now, again for the sake of illustration, consider that the species &lt;code&gt;Adelie&lt;/code&gt; is the reference species and we are only interested in comparing the reference species against the other 2 species. In that scenario, we would use the Dunnett’s test.&lt;/p&gt;
&lt;p&gt;In R, the Dunnett’s test is done as follows (the only difference with the code for the Tukey HSD test is in the line &lt;code&gt;linfct = mcp(species = &#34;Dunnett&#34;)&lt;/code&gt;):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(multcomp)

# Dunnett&amp;#39;s test:
post_test &amp;lt;- glht(res_aov,
  linfct = mcp(species = &amp;quot;Dunnett&amp;quot;)
)

summary(post_test)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	 Simultaneous Tests for General Linear Hypotheses
## 
## Multiple Comparisons of Means: Dunnett Contrasts
## 
## 
## Fit: aov(formula = flipper_length_mm ~ species, data = dat)
## 
## Linear Hypotheses:
##                         Estimate Std. Error t value Pr(&amp;gt;|t|)    
## Chinstrap - Adelie == 0   5.8699     0.9699   6.052 7.59e-09 ***
## Gentoo - Adelie == 0     27.2333     0.8067  33.760  &amp;lt; 1e-10 ***
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## (Adjusted p values reported -- single-step method)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The interpretation is the same as for the Tukey HSD test’s except that in the Dunett’s test we only compare:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Chinstrap versus Adelie (line &lt;code&gt;Chinstrap - Adelie == 0&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;Gentoo vs. Adelie (line &lt;code&gt;Gentoo - Adelie == 0&lt;/code&gt;)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Both adjusted &lt;em&gt;p&lt;/em&gt;-values (displayed in the last column) are below 0.05, so we reject the null hypothesis for both comparisons.&lt;/p&gt;
&lt;p&gt;This means that both the &lt;strong&gt;species Chinstrap and Gentoo are significantly different from the reference species Adelie&lt;/strong&gt; in terms of flippers length. (Nothing can be said about the comparison between Chinstrap and Gentoo though.)&lt;/p&gt;
&lt;p&gt;Again, the results of the post-hoc test can be visualized with the &lt;code&gt;plot()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;par(mar = c(3, 8, 3, 3))
plot(post_test)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/figure-html/unnamed-chunk-25-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;We see that the confidence intervals do not cross the zero line, which indicate that both the species Gentoo and Chinstrap are significantly different from the reference species Adelie.&lt;/p&gt;
&lt;p&gt;Note that in R, by default, the reference category for a &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#factor&#34;&gt;factor variable&lt;/a&gt; is the first category in alphabetical order. This is the reason that, by default, the reference species is Adelie.&lt;/p&gt;
&lt;p&gt;The reference category can be changed with the &lt;code&gt;relevel()&lt;/code&gt; function (or with the &lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#reordering-factors&#34;&gt;&lt;code&gt;{questionr}&lt;/code&gt; addin&lt;/a&gt;). Considering that we want Gentoo as the reference category instead of Adelie:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Change reference category:
dat$species &amp;lt;- relevel(dat$species, ref = &amp;quot;Gentoo&amp;quot;)

# Check that Gentoo is the reference category:
levels(dat$species)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;Gentoo&amp;quot;    &amp;quot;Adelie&amp;quot;    &amp;quot;Chinstrap&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Gentoo now being the first category of the three, it is indeed considered as the reference level.&lt;/p&gt;
&lt;p&gt;In order to perform the Dunnett’s test with the new reference we first need to rerun the ANOVA to take into account the new reference:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;res_aov2 &amp;lt;- aov(flipper_length_mm ~ species,
  data = dat
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can then run the Dunett’s test with the new results of the ANOVA:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Dunnett&amp;#39;s test:
post_test &amp;lt;- glht(res_aov2,
  linfct = mcp(species = &amp;quot;Dunnett&amp;quot;)
)

summary(post_test)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	 Simultaneous Tests for General Linear Hypotheses
## 
## Multiple Comparisons of Means: Dunnett Contrasts
## 
## 
## Fit: aov(formula = flipper_length_mm ~ species, data = dat)
## 
## Linear Hypotheses:
##                         Estimate Std. Error t value Pr(&amp;gt;|t|)    
## Adelie - Gentoo == 0    -27.2333     0.8067  -33.76   &amp;lt;1e-10 ***
## Chinstrap - Gentoo == 0 -21.3635     1.0036  -21.29   &amp;lt;1e-10 ***
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1
## (Adjusted p values reported -- single-step method)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;par(mar = c(3, 8, 3, 3))
plot(post_test)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/figure-html/unnamed-chunk-28-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;From the results above we conclude that Adelie and Chinstrap species are significantly different from Gentoo species in terms of flippers length (adjusted &lt;em&gt;p&lt;/em&gt;-values &amp;lt; 1e-10).&lt;/p&gt;
&lt;p&gt;Note that even if your study does not have a reference group which you can compare to the other groups, it is still often better to do multiple comparisons determined by some research questions than to do all-pairwise tests. By reducing the number of post-hoc comparisons to what is necessary only, and no more, you maximize the statistical power.&lt;a href=&#34;#fn8&#34; class=&#34;footnote-ref&#34; id=&#34;fnref8&#34;&gt;&lt;sup&gt;8&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;other-p-values-adjustment-methods&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Other &lt;em&gt;p&lt;/em&gt;-values adjustment methods&lt;/h2&gt;
&lt;p&gt;For the interested readers, note that you can use other &lt;em&gt;p&lt;/em&gt;-values adjustment methods by using the &lt;code&gt;pairwise.t.test()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;pairwise.t.test(dat$flipper_length_mm, dat$species,
  p.adjust.method = &amp;quot;holm&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Pairwise comparisons using t tests with pooled SD 
## 
## data:  dat$flipper_length_mm and dat$species 
## 
##           Gentoo  Adelie 
## Adelie    &amp;lt; 2e-16 -      
## Chinstrap &amp;lt; 2e-16 3.8e-09
## 
## P value adjustment method: holm&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By default, the Holm method is applied but other methods exist. See &lt;code&gt;?p.adjust&lt;/code&gt; for all available options.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;visualization-of-anova-and-post-hoc-tests-on-the-same-plot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Visualization of ANOVA and post-hoc tests on the same plot&lt;/h1&gt;
&lt;p&gt;If you are interested in including results of ANOVA and post-hoc tests on the same plot (directly on the boxplots), here are two pieces of code which may be of interest to you.&lt;/p&gt;
&lt;p&gt;The first one is edited by me based on the code found in this &lt;a href=&#34;http://www.sthda.com/english/articles/24-ggpubr-publication-ready-plots/76-add-p-values-and-significance-levels-to-ggplots/&#34; target=&#34;_blank&#34;&gt;article&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Edit from here
x &amp;lt;- which(names(dat) == &amp;quot;species&amp;quot;) # name of grouping variable
y &amp;lt;- which(
  names(dat) == &amp;quot;flipper_length_mm&amp;quot; # names of variables to test
)
method1 &amp;lt;- &amp;quot;anova&amp;quot; # one of &amp;quot;anova&amp;quot; or &amp;quot;kruskal.test&amp;quot;
method2 &amp;lt;- &amp;quot;t.test&amp;quot; # one of &amp;quot;wilcox.test&amp;quot; or &amp;quot;t.test&amp;quot;
my_comparisons &amp;lt;- list(c(&amp;quot;Chinstrap&amp;quot;, &amp;quot;Adelie&amp;quot;), c(&amp;quot;Gentoo&amp;quot;, &amp;quot;Adelie&amp;quot;), c(&amp;quot;Gentoo&amp;quot;, &amp;quot;Chinstrap&amp;quot;)) # comparisons for post-hoc tests
# Edit until here


# Edit at your own risk
library(ggpubr)
for (i in y) {
  for (j in x) {
    p &amp;lt;- ggboxplot(dat,
      x = colnames(dat[j]), y = colnames(dat[i]),
      color = colnames(dat[j]),
      legend = &amp;quot;none&amp;quot;,
      palette = &amp;quot;npg&amp;quot;,
      add = &amp;quot;jitter&amp;quot;
    )
    print(
      p + stat_compare_means(aes(label = paste0(after_stat(method), &amp;quot;, p-value = &amp;quot;, after_stat(p.format))),
        method = method1, label.y = max(dat[, i], na.rm = TRUE)
      )
      + stat_compare_means(comparisons = my_comparisons, method = method2, label = &amp;quot;p.format&amp;quot;) # remove if p-value of ANOVA or Kruskal-Wallis test &amp;gt;= alpha
    )
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/figure-html/unnamed-chunk-30-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;And the second method is from the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggstatsplot)

ggbetweenstats(
  data = dat,
  x = species,
  y = flipper_length_mm,
  type = &amp;quot;parametric&amp;quot;, # ANOVA or Kruskal-Wallis
  var.equal = TRUE, # ANOVA or Welch ANOVA
  plot.type = &amp;quot;box&amp;quot;,
  pairwise.comparisons = TRUE,
  pairwise.display = &amp;quot;significant&amp;quot;,
  centrality.plotting = FALSE,
  bf.message = FALSE
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-10-12-anova-in-r_files/figure-html/unnamed-chunk-31-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;As you can see on the above plot, boxplots by species are presented together with &lt;em&gt;p&lt;/em&gt;-values of the ANOVA (after &lt;code&gt;p =&lt;/code&gt; in the subtitle of the plot) and &lt;em&gt;p&lt;/em&gt;-values of the post-hoc tests (above each comparison).&lt;/p&gt;
&lt;p&gt;Besides the fact that these methods can be used to combine a visual representation and statistical results on the same plot, they also have the advantage that you can perform multiple ANOVA tests at once. See more information in this &lt;a href=&#34;https://statsandr.com/blog/how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way/&#34;&gt;article&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;summary&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;In this article, we reviewed the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#aim-and-hypotheses-of-anova&#34;&gt;goals and hypotheses&lt;/a&gt; of an ANOVA, what are the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#underlying-assumptions-of-anova&#34;&gt;assumptions&lt;/a&gt; which need to be verified before being able to trust the results (namely, independence, normality and homogeneity), we then showed &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#anova-in-r&#34;&gt;how to do an ANOVA in R&lt;/a&gt; and how to &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#interpretations-of-anova-results&#34;&gt;interpret the results&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;An article about ANOVA would not be complete without discussing about &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#post-hoc-test&#34;&gt;post-hoc tests&lt;/a&gt;, and in particular, the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#tukey-hsd-test&#34;&gt;Tukey HSD&lt;/a&gt;—to compare all groups—and the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#dunnetts-test&#34;&gt;Dunnett’s&lt;/a&gt; test—to compare a reference group to all other groups.&lt;/p&gt;
&lt;p&gt;Last but not least, we showed how to &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#visualization-of-anova-and-post-hoc-tests&#34;&gt;visualize&lt;/a&gt; the data and the results of the ANOVA and post-hoc tests in the same plot.&lt;/p&gt;
&lt;p&gt;Thanks for reading. See this &lt;a href=&#34;https://statsandr.com/blog/how-to-one-way-anova-by-hand/&#34;&gt;tutorial&lt;/a&gt; if you would like to learn how to do an ANOVA by hand.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;(Note that this article is available for download on my &lt;a href=&#34;https://statsandr.gumroad.com/&#34;&gt;Gumroad page&lt;/a&gt;.)&lt;/em&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-hsu1996multiple&#34; class=&#34;csl-entry&#34;&gt;
Hsu, Jason. 1996. &lt;em&gt;Multiple Comparisons: Theory and Methods&lt;/em&gt;. CRC Press.
&lt;/div&gt;
&lt;div id=&#34;ref-stevens2013intermediate&#34; class=&#34;csl-entry&#34;&gt;
Stevens, James P. 2013. &lt;em&gt;Intermediate Statistics: A Modern Approach&lt;/em&gt;. Routledge.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;Note that it is called &lt;em&gt;one-way&lt;/em&gt; or &lt;em&gt;one-factor&lt;/em&gt; ANOVA because the means relate to the different modalities of a single independent variable, or factor.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Residuals (denoted &lt;span class=&#34;math inline&#34;&gt;\(\epsilon\)&lt;/span&gt;) are the differences between the observed values of the dependent variable (&lt;span class=&#34;math inline&#34;&gt;\(y\)&lt;/span&gt;) and the predicted values (&lt;span class=&#34;math inline&#34;&gt;\(\hat{y}\)&lt;/span&gt;). In the context of ANOVA, residuals correspond to the differences between the observed values and the mean of all values for that group.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;&lt;span class=&#34;citation&#34;&gt;Stevens (&lt;a href=&#34;#ref-stevens2013intermediate&#34;&gt;2013&lt;/a&gt;)&lt;/span&gt; wrote, in p. 57, “Numerous studies have examined the effect of violations of assumptions in ANOVA, and an excellent summary of this literature has been provided by Glass, Peckham, and Sanders (1972). Their review indicates that non normality has only a slight effect on the type I error rate, even for very skewed or kurtotic distributions. For example, the actual &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;s for some very non-normal populations were only .055 or .06: very minor deviations from the nominal level of .05. […] The basic reason is the &lt;em&gt;Central Limit Theorem&lt;/em&gt;, which states that the sum of independent observations having any distribution whatsoever approaches a normal distribution as the number of observations increases. To be somewhat more specific, Bock (1975) notes,”even for distributions which depart markedly from normality, sums of 50 or more observations approximate to normality. For moderately non-normal distributions the approximation is good with as few as 10 to 20 observations” (p. 111). Now since the sums of independent observations approach normality rapidly, so do the means, and the sampling distribution of &lt;em&gt;F&lt;/em&gt; is based on means. Thus the sampling distribution of &lt;em&gt;F&lt;/em&gt; is only slightly affected, and therefore the critical values when sampling from normal and non-normal distributions will not differ by much. Lack of normality due to skewness also has only a slight effect on power (a few hundredths).”&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;As long as you use the Kruskal-Wallis test to, &lt;em&gt;in fine&lt;/em&gt;, compare groups, homoscedasticity is not required. If you wish to compare medians, the Kruskal-Wallis test requires homoscedasticity. See more information about the difference in this &lt;a href=&#34;https://influentialpoints.com/Training/Kruskal-Wallis_ANOVA_use_and_misuse.htm&#34; target=&#34;_blank&#34;&gt;article&lt;/a&gt;.&lt;a href=&#34;#fnref4&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn5&#34;&gt;&lt;p&gt;Note that, as discussed in the comments at the end of the article, post-hoc tests can under some circumstances be done directly (without an ANOVA). See the comments or &lt;span class=&#34;citation&#34;&gt;Hsu (&lt;a href=&#34;#ref-hsu1996multiple&#34;&gt;1996&lt;/a&gt;)&lt;/span&gt; for more details.&lt;a href=&#34;#fnref5&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn6&#34;&gt;&lt;p&gt;Note that you could in principle apply the Bonferroni correction to all tests. For example, in the example above, with 3 tests and a global desired significance level of &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; = 0.05, we would only reject a null hypothesis if the &lt;em&gt;p&lt;/em&gt;-value is less than &lt;span class=&#34;math inline&#34;&gt;\(\frac{0.05}{3}\)&lt;/span&gt; = 0.0167. This method is, however, known to be quite conservative, leading to a potentially high rate of false negatives.&lt;a href=&#34;#fnref6&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn7&#34;&gt;&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-values are adjusted to keep the global significance level to the desired level.&lt;a href=&#34;#fnref7&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn8&#34;&gt;&lt;p&gt;Thanks Michael Friendly for this suggestion.&lt;a href=&#34;#fnref8&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Outliers detection in R</title>
      <link>https://statsandr.com/blog/outliers-detection-in-r/</link>
      <pubDate>Tue, 11 Aug 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/outliers-detection-in-r/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#descriptive-statistics&#34; id=&#34;toc-descriptive-statistics&#34;&gt;Descriptive statistics&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#minimum-and-maximum&#34; id=&#34;toc-minimum-and-maximum&#34;&gt;Minimum and maximum&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#histogram&#34; id=&#34;toc-histogram&#34;&gt;Histogram&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#boxplot&#34; id=&#34;toc-boxplot&#34;&gt;Boxplot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#percentiles&#34; id=&#34;toc-percentiles&#34;&gt;Percentiles&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#z-scores&#34; id=&#34;toc-z-scores&#34;&gt;Z-scores&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#hampel-filter&#34; id=&#34;toc-hampel-filter&#34;&gt;Hampel filter&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#statistical-tests&#34; id=&#34;toc-statistical-tests&#34;&gt;Statistical tests&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#grubbss-test&#34; id=&#34;toc-grubbss-test&#34;&gt;Grubbs’s test&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#dixons-test&#34; id=&#34;toc-dixons-test&#34;&gt;Dixon’s test&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#rosners-test&#34; id=&#34;toc-rosners-test&#34;&gt;Rosner’s test&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#additional-remarks&#34; id=&#34;toc-additional-remarks&#34;&gt;Additional remarks&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-08-11-outliers-detection-in-r_files/outliers-detection-in-R.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;An &lt;strong&gt;outlier&lt;/strong&gt; is a value or an &lt;strong&gt;observation that is distant from other observations&lt;/strong&gt;, that is to say, a data point that differs significantly from other data points. &lt;span class=&#34;citation&#34;&gt;Enderlein (&lt;a href=&#34;#ref-enderlein1987hawkins&#34;&gt;1987&lt;/a&gt;)&lt;/span&gt; goes even further as the author considers outliers as values that deviate so much from other observations one might suppose a different underlying sampling mechanism.&lt;/p&gt;
&lt;p&gt;An observation must always be compared to other observations made on the same phenomenon before actually calling it an outlier. Indeed, someone who is 200 cm tall (6’7” in US) will most likely be considered as an outlier compared to the general population, but that same person may not be considered as an outlier if we measured the height of basketball players.&lt;/p&gt;
&lt;p&gt;An outlier may be due to the variability inherent in the observed phenomenon. For example, it is often the case that there are outliers when collecting data on salaries, as some people make much more money than the rest.&lt;/p&gt;
&lt;p&gt;Outliers can also arise due to an experimental, measurement or encoding error. For instance, a human weighting 786 kg (1733 pounds) is clearly an error when encoding the weight of the subject. Her or his weight is most probably 78.6 kg (173 pounds) or 7.86 kg (17 pounds) depending on whether weights of adults or babies have been measured.&lt;/p&gt;
&lt;p&gt;For this reason, it sometimes makes sense to formally distinguish two classes of outliers: (i) extreme values and (ii) mistakes. Extreme values are statistically and philosophically more interesting, because they are possible but unlikely responses.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In this article, I present several approaches to detect outliers in R, from simple techniques such as &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt; (including minimum, maximum, histogram, boxplot and percentiles) to more formal techniques such as the Hampel filter, the Grubbs, the Dixon and the Rosner tests for outliers.&lt;/p&gt;
&lt;p&gt;Although there is no strict or unique rule whether outliers should be removed or not from the dataset before doing statistical analyses, it is quite common to, at least, remove or impute outliers that are due to an experimental or measurement error (like the weight of 786 kg (1733 pounds) for a human). Some &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt; require the absence of outliers in order to draw sound conclusions, but removing outliers is not recommended in all cases and must be done with caution.&lt;/p&gt;
&lt;p&gt;This article will not tell you whether you should remove outliers or not (nor if you should impute them with the median, mean, mode or any other value), but it will help you to detect them in order to, as a first step, verify them. After their verification, it is then your choice to exclude or include them for your analyses (and this usually requires a thoughtful reflection on the researcher’s side).&lt;/p&gt;
&lt;p&gt;Removing or keeping outliers mostly depend on three factors:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;The domain/context of your analyses and the research question. In some domains, it is common to remove outliers as they often occur due to a malfunctioning process. In other fields, outliers are kept because they contain valuable information. It also happens that analyses are performed twice, once with and once without outliers to evaluate their impact on the conclusions. If results change drastically due to some influential values, this should caution the researcher to make overambitious claims.&lt;/li&gt;
&lt;li&gt;Whether the tests you are going to apply are robust to the presence of outliers or not. For instance, the slope of a simple &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;linear regression&lt;/a&gt; may significantly varies with just one outlier, whereas non-parametric tests such as the &lt;a href=&#34;https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/&#34;&gt;Wilcoxon test&lt;/a&gt; are usually robust to outliers.&lt;/li&gt;
&lt;li&gt;How distant are the outliers from other observations? Some observations considered as outliers (according to the techniques presented below) are actually not really extreme compared to all other observations, while other potential outliers may be really distant from the rest of the observations.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The dataset &lt;code&gt;mpg&lt;/code&gt; from the &lt;code&gt;{ggplot2}&lt;/code&gt; package will be used to illustrate the different approaches of outliers detection in R, and in particular we will focus on the variable &lt;code&gt;hwy&lt;/code&gt; (highway miles per gallon). We will also use some simulated data for the presentation of the outlier tests.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;descriptive-statistics&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Descriptive statistics&lt;/h1&gt;
&lt;p&gt;Several methods using descriptive statistics exist. We present the most common ones below.&lt;/p&gt;
&lt;div id=&#34;minimum-and-maximum&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Minimum and maximum&lt;/h2&gt;
&lt;p&gt;The first step to detect outliers in R is to start with some &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt;, and in particular with the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#minimum-and-maximum&#34;&gt;minimum and maximum&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;In R, this can easily be done with the &lt;code&gt;summary()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- ggplot2::mpg
summary(dat$hwy)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   12.00   18.00   24.00   23.44   27.00   44.00&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;where the minimum and maximum are respectively the first and last values in the output above.&lt;/p&gt;
&lt;p&gt;Alternatively, they can also be computed with the &lt;code&gt;min()&lt;/code&gt; and &lt;code&gt;max()&lt;/code&gt;, or &lt;code&gt;range()&lt;/code&gt; functions:&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;min(dat$hwy)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 12&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;max(dat$hwy)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 44&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;range(dat$hwy)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 12 44&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Some clear encoding mistake like a weight of 786 kg (1733 pounds) for a human will already be easily detected by this very simple technique.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;histogram&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Histogram&lt;/h2&gt;
&lt;p&gt;Another basic way to detect outliers is to draw a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt; of the data.&lt;/p&gt;
&lt;p&gt;Using R base (with the number of bins corresponding to the square root of the number of observations in order to have more bins than the default option):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;hist(dat$hwy,
  xlab = &amp;quot;hwy&amp;quot;,
  main = &amp;quot;Histogram of hwy&amp;quot;,
  breaks = sqrt(length(dat$hwy)) # set number of bins
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-08-11-outliers-detection-in-r_files/figure-html/unnamed-chunk-3-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;or using &lt;code&gt;ggplot2&lt;/code&gt; (learn how to create plots with this package via the &lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#esquisse&#34;&gt;&lt;code&gt;esquisse&lt;/code&gt; addin&lt;/a&gt; or via this &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;tutorial&lt;/a&gt;):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggplot2)

ggplot(dat) +
  aes(x = hwy) +
  geom_histogram(
    bins = round(sqrt(length(dat$hwy))), # set number of bins
    fill = &amp;quot;steelblue&amp;quot;, color = &amp;quot;black&amp;quot;
  ) +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-08-11-outliers-detection-in-r_files/figure-html/unnamed-chunk-4-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;From the histograms, we see that there seems to be a couple of observations larger than all other observations (see the bars on the right side of the plot).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;boxplot&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Boxplot&lt;/h2&gt;
&lt;p&gt;In addition to histograms, &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#boxplot&#34;&gt;boxplots&lt;/a&gt; are also useful to detect potential outliers.&lt;/p&gt;
&lt;p&gt;Using R base:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;boxplot(dat$hwy,
  ylab = &amp;quot;hwy&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-08-11-outliers-detection-in-r_files/figure-html/unnamed-chunk-5-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;or using &lt;code&gt;ggplot2&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = &amp;quot;&amp;quot;, y = hwy) +
  geom_boxplot(fill = &amp;quot;steelblue&amp;quot;) +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-08-11-outliers-detection-in-r_files/figure-html/unnamed-chunk-6-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;A boxplot helps to visualize a quantitative variable by displaying five common location summary (minimum, median, first and third quartiles and maximum) and any observation that was classified as a suspected outlier using the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#interquartile-range&#34;&gt;interquartile range (IQR)&lt;/a&gt; criterion.&lt;/p&gt;
&lt;p&gt;The IQR criterion means that all observations above &lt;span class=&#34;math inline&#34;&gt;\(q_{0.75} + 1.5 \cdot IQR\)&lt;/span&gt; or below &lt;span class=&#34;math inline&#34;&gt;\(q_{0.25} - 1.5 \cdot IQR\)&lt;/span&gt; (where &lt;span class=&#34;math inline&#34;&gt;\(q_{0.25}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(q_{0.75}\)&lt;/span&gt; correspond to first and third quartile respectively, and IQR is the difference between the third and first quartile) are considered as potential outliers by R.&lt;/p&gt;
&lt;p&gt;In other words, all observations outside of the following interval will be considered as potential outliers:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[I = [q_{0.25} - 1.5 \cdot IQR; q_{0.75} + 1.5 \cdot IQR]\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Observations considered as potential outliers by the IQR criterion are displayed as points in the boxplot. Based on this criterion, there are 2 potential outliers (see the 2 points above the vertical line, at the top of the boxplot).&lt;/p&gt;
&lt;p&gt;Remember that it is not because an observation is considered as a potential outlier by the IQR criterion that you should remove it. Removing or keeping an outlier depends on:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;the context of your analysis,&lt;/li&gt;
&lt;li&gt;whether the tests you are going to perform on the dataset are robust to outliers or not, and&lt;/li&gt;
&lt;li&gt;how extreme is the outlier (so how far is the outlier from other observations).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;It is also possible to extract the values of the potential outliers based on the IQR criterion thanks to the &lt;code&gt;boxplot.stats()$out&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;boxplot.stats(dat$hwy)$out&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 44 44 41&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, there are actually 3 points considered as potential outliers: 2 observations with a value of 44 and 1 observation with a value of 41.&lt;/p&gt;
&lt;p&gt;Thanks to the &lt;code&gt;which()&lt;/code&gt; function it is possible to extract the row number corresponding to these outliers:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;out &amp;lt;- boxplot.stats(dat$hwy)$out
out_ind &amp;lt;- which(dat$hwy %in% c(out))
out_ind&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 213 222 223&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With this information you can now easily go back to the specific rows in the dataset to verify them, or print all variables for these outliers:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat[out_ind, ]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 11
##   manufacturer model      displ  year   cyl trans  drv     cty   hwy fl    class
##   &amp;lt;chr&amp;gt;        &amp;lt;chr&amp;gt;      &amp;lt;dbl&amp;gt; &amp;lt;int&amp;gt; &amp;lt;int&amp;gt; &amp;lt;chr&amp;gt;  &amp;lt;chr&amp;gt; &amp;lt;int&amp;gt; &amp;lt;int&amp;gt; &amp;lt;chr&amp;gt; &amp;lt;chr&amp;gt;
## 1 volkswagen   jetta        1.9  1999     4 manua… f        33    44 d     comp…
## 2 volkswagen   new beetle   1.9  1999     4 manua… f        35    44 d     subc…
## 3 volkswagen   new beetle   1.9  1999     4 auto(… f        29    41 d     subc…&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Another method to display these specific rows is with the &lt;code&gt;identify_outliers()&lt;/code&gt; function from the &lt;code&gt;{rstatix}&lt;/code&gt; package:&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(rstatix)

identify_outliers(
  data = dat,
  variable = &amp;quot;hwy&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 13
##   manufacturer model      displ  year   cyl trans  drv     cty   hwy fl    class
##   &amp;lt;chr&amp;gt;        &amp;lt;chr&amp;gt;      &amp;lt;dbl&amp;gt; &amp;lt;int&amp;gt; &amp;lt;int&amp;gt; &amp;lt;chr&amp;gt;  &amp;lt;chr&amp;gt; &amp;lt;int&amp;gt; &amp;lt;int&amp;gt; &amp;lt;chr&amp;gt; &amp;lt;chr&amp;gt;
## 1 volkswagen   jetta        1.9  1999     4 manua… f        33    44 d     comp…
## 2 volkswagen   new beetle   1.9  1999     4 manua… f        35    44 d     subc…
## 3 volkswagen   new beetle   1.9  1999     4 auto(… f        29    41 d     subc…
## # ℹ 2 more variables: is.outlier &amp;lt;lgl&amp;gt;, is.extreme &amp;lt;lgl&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is also possible to print the values of the outliers directly on the boxplot with the &lt;code&gt;mtext()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;boxplot(dat$hwy,
  ylab = &amp;quot;hwy&amp;quot;,
  main = &amp;quot;Boxplot of highway miles per gallon&amp;quot;
)
mtext(paste(&amp;quot;Outliers: &amp;quot;, paste(out, collapse = &amp;quot;, &amp;quot;)))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-08-11-outliers-detection-in-r_files/figure-html/unnamed-chunk-11-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;percentiles&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Percentiles&lt;/h2&gt;
&lt;p&gt;This method of outliers detection is based on the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#a-note-on-deciles-and-percentiles&#34;&gt;percentiles&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;With the percentiles method, all observations that lie outside the interval formed by the 2.5 and 97.5 percentiles will be considered as potential outliers. Other percentiles such as the 1 and 99, or the 5 and 95 percentiles can also be considered to construct the interval.&lt;/p&gt;
&lt;p&gt;The values of the lower and upper percentiles (and thus the lower and upper limits of the interval) can be computed with the &lt;code&gt;quantile()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;lower_bound &amp;lt;- quantile(dat$hwy, 0.025)
lower_bound&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 2.5% 
##   14&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;upper_bound &amp;lt;- quantile(dat$hwy, 0.975)
upper_bound&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  97.5% 
## 35.175&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;According to this method, all observations below 14 and above 35.175 will be considered as potential outliers. The row numbers of the observations outside of the interval can then be extracted with the &lt;code&gt;which()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;outlier_ind &amp;lt;- which(dat$hwy &amp;lt; lower_bound | dat$hwy &amp;gt; upper_bound)
outlier_ind&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1]  55  60  66  70 106 107 127 197 213 222 223&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then their values of highway miles per gallon can be printed:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat[outlier_ind, &amp;quot;hwy&amp;quot;]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 11 × 1
##      hwy
##    &amp;lt;int&amp;gt;
##  1    12
##  2    12
##  3    12
##  4    12
##  5    36
##  6    36
##  7    12
##  8    37
##  9    44
## 10    44
## 11    41&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Alternatively, all variables for these outliers can be printed:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat[outlier_ind, ]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 11 × 11
##    manufacturer model      displ  year   cyl trans drv     cty   hwy fl    class
##    &amp;lt;chr&amp;gt;        &amp;lt;chr&amp;gt;      &amp;lt;dbl&amp;gt; &amp;lt;int&amp;gt; &amp;lt;int&amp;gt; &amp;lt;chr&amp;gt; &amp;lt;chr&amp;gt; &amp;lt;int&amp;gt; &amp;lt;int&amp;gt; &amp;lt;chr&amp;gt; &amp;lt;chr&amp;gt;
##  1 dodge        dakota pi…   4.7  2008     8 auto… 4         9    12 e     pick…
##  2 dodge        durango 4…   4.7  2008     8 auto… 4         9    12 e     suv  
##  3 dodge        ram 1500 …   4.7  2008     8 auto… 4         9    12 e     pick…
##  4 dodge        ram 1500 …   4.7  2008     8 manu… 4         9    12 e     pick…
##  5 honda        civic        1.8  2008     4 auto… f        25    36 r     subc…
##  6 honda        civic        1.8  2008     4 auto… f        24    36 c     subc…
##  7 jeep         grand che…   4.7  2008     8 auto… 4         9    12 e     suv  
##  8 toyota       corolla      1.8  2008     4 manu… f        28    37 r     comp…
##  9 volkswagen   jetta        1.9  1999     4 manu… f        33    44 d     comp…
## 10 volkswagen   new beetle   1.9  1999     4 manu… f        35    44 d     subc…
## 11 volkswagen   new beetle   1.9  1999     4 auto… f        29    41 d     subc…&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There are 11 potential outliers according to the percentiles method. To reduce this number, you can set the percentiles to 1 and 99:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;lower_bound &amp;lt;- quantile(dat$hwy, 0.01)
upper_bound &amp;lt;- quantile(dat$hwy, 0.99)

outlier_ind &amp;lt;- which(dat$hwy &amp;lt; lower_bound | dat$hwy &amp;gt; upper_bound)

dat[outlier_ind, ]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 11
##   manufacturer model      displ  year   cyl trans  drv     cty   hwy fl    class
##   &amp;lt;chr&amp;gt;        &amp;lt;chr&amp;gt;      &amp;lt;dbl&amp;gt; &amp;lt;int&amp;gt; &amp;lt;int&amp;gt; &amp;lt;chr&amp;gt;  &amp;lt;chr&amp;gt; &amp;lt;int&amp;gt; &amp;lt;int&amp;gt; &amp;lt;chr&amp;gt; &amp;lt;chr&amp;gt;
## 1 volkswagen   jetta        1.9  1999     4 manua… f        33    44 d     comp…
## 2 volkswagen   new beetle   1.9  1999     4 manua… f        35    44 d     subc…
## 3 volkswagen   new beetle   1.9  1999     4 auto(… f        29    41 d     subc…&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Setting the percentiles to 1 and 99 gives the same potential outliers as with the IQR criterion.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;z-scores&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Z-scores&lt;/h2&gt;
&lt;p&gt;If your data come from a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution&lt;/a&gt;, you can use the z-scores, defined as&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[z_i = \frac{x_i - \overline{X}}{s_X}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(\overline{X}\)&lt;/span&gt; is the mean and &lt;span class=&#34;math inline&#34;&gt;\(s_X\)&lt;/span&gt; is the standard deviation of the random variable &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;This is referred as scaling, which can be done with the &lt;code&gt;scale()&lt;/code&gt; function in R.&lt;/p&gt;
&lt;p&gt;According to this method, any z-score:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&amp;lt; -2 or &amp;gt; 2 is considered as rare&lt;/li&gt;
&lt;li&gt;&amp;lt; -3 or &amp;gt; 3 is considered as extremely rare&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Other authors also use a z-score below -3.29 or above 3.29 to detect outliers. This value of 3.29 comes from the fact that 1 observation out of 1000 is out of this interval if the data follow a normal distribution.&lt;/p&gt;
&lt;p&gt;In our case:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat$z_hwy &amp;lt;- scale(dat$hwy)

hist(dat$z_hwy)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-08-11-outliers-detection-in-r_files/figure-html/unnamed-chunk-17-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(dat$z_hwy)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##        V1          
##  Min.   :-1.92122  
##  1st Qu.:-0.91360  
##  Median : 0.09402  
##  Mean   : 0.00000  
##  3rd Qu.: 0.59782  
##  Max.   : 3.45274&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We see that there are some observations above 3.29, but none below -3.29.&lt;/p&gt;
&lt;p&gt;To identify the line in the dataset of these observations:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;which(dat$z_hwy &amp;gt; 3.29)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 213 222&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We see that observations 213 and 222 can be considered as outliers according to this method.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;hampel-filter&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Hampel filter&lt;/h1&gt;
&lt;p&gt;Another method, known as Hampel filter, consists of considering as outliers the values outside the interval (&lt;span class=&#34;math inline&#34;&gt;\(I\)&lt;/span&gt;) formed by the median, plus or minus 3 median absolute deviations (&lt;span class=&#34;math inline&#34;&gt;\(MAD\)&lt;/span&gt;):&lt;a href=&#34;#fn4&#34; class=&#34;footnote-ref&#34; id=&#34;fnref4&#34;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[I = [median - 3 \cdot MAD; median + 3 \cdot MAD]\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(MAD\)&lt;/span&gt; is the median absolute deviation and is defined as the median of the absolute deviations from the data’s median &lt;span class=&#34;math inline&#34;&gt;\(\tilde{X} = median(X)\)&lt;/span&gt;:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[MAD = median(|X_i - \tilde{X}|)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For this method we first set the interval limits thanks to the &lt;code&gt;median()&lt;/code&gt; and &lt;code&gt;mad()&lt;/code&gt; functions:&lt;a href=&#34;#fn5&#34; class=&#34;footnote-ref&#34; id=&#34;fnref5&#34;&gt;&lt;sup&gt;5&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;lower_bound &amp;lt;- median(dat$hwy) - 3 * mad(dat$hwy, constant = 1)
lower_bound&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 9&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;upper_bound &amp;lt;- median(dat$hwy) + 3 * mad(dat$hwy, constant = 1)
upper_bound&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 39&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;According to this method, all observations below 9 and above 39 will be considered as potential outliers. The row numbers of the observations outside of the interval can then be extracted with the &lt;code&gt;which()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;outlier_ind &amp;lt;- which(dat$hwy &amp;lt; lower_bound | dat$hwy &amp;gt; upper_bound)
outlier_ind&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 213 222 223&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;According to the Hampel filter, there are 3 outliers for the &lt;code&gt;hwy&lt;/code&gt; variable.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;statistical-tests&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Statistical tests&lt;/h1&gt;
&lt;p&gt;In this section, we present 3 &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt; to detect outliers:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Grubbs’s test&lt;/li&gt;
&lt;li&gt;Dixon’s test&lt;/li&gt;
&lt;li&gt;Rosner’s test&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;These 3 statistical tests are part of more formal techniques of outliers detection as they all involve the computation of a test statistic that is compared to tabulated critical values (that are based on the sample size and the desired confidence level).&lt;/p&gt;
&lt;p&gt;Note that the 3 tests are appropriate only when the data, without any outliers, are &lt;strong&gt;approximately normally distributed&lt;/strong&gt;. It is recommended to check normality visually, with a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#qq-plot&#34;&gt;QQ-plot&lt;/a&gt;, a histogram and/or a boxplot for instance. Although it can also be checked with a formal test for normality (such as the &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#normality-test&#34;&gt;Shapiro-Wilk test&lt;/a&gt; for example), the presence of one or more outliers may cause the normality test to reject normality when it is in fact a reasonable assumption for applying one of the 3 outlier tests mentioned above.&lt;/p&gt;
&lt;p&gt;We check the normality of our data thanks to a QQ-plot:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(car)
qqPlot(dat$hwy)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-08-11-outliers-detection-in-r_files/figure-html/unnamed-chunk-21-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## [1] 213 222&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Too many points deviate from the Henry’s line, so based on the QQ-plot we conclude that our data do not follow a normal distribution. Therefore, we should not use one of the outlier test on these data.&lt;/p&gt;
&lt;p&gt;For the sake of completeness, here is an example of data that could be used with the three outlier tests, together with the QQ-plot of these data:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat_tests &amp;lt;- c(rnorm(50), 5)

qqPlot(dat_tests)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-08-11-outliers-detection-in-r_files/figure-html/unnamed-chunk-22-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## [1] 51 18&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;hist(dat_tests)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-08-11-outliers-detection-in-r_files/figure-html/unnamed-chunk-22-2.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;For the illustration of the three outlier tests in the next sections, we thus use the simulated data (&lt;code&gt;dat_tests&lt;/code&gt;) instead of the data used so far (&lt;code&gt;dat$hwy&lt;/code&gt;).&lt;/p&gt;
&lt;div id=&#34;grubbss-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Grubbs’s test&lt;/h2&gt;
&lt;p&gt;The Grubbs test allows to detect whether the highest or lowest value in a dataset is an outlier.&lt;/p&gt;
&lt;p&gt;The Grubbs test detects one outlier at a time (highest or lowest value), so the null and alternative hypotheses are as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: The &lt;em&gt;highest&lt;/em&gt; value is &lt;strong&gt;not&lt;/strong&gt; an outlier&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: The &lt;em&gt;highest&lt;/em&gt; value is an outlier&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;if we want to test the highest value, or:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: The &lt;em&gt;lowest&lt;/em&gt; value is &lt;strong&gt;not&lt;/strong&gt; an outlier&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: The &lt;em&gt;lowest&lt;/em&gt; value is an outlier&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;if we want to test the lowest value.&lt;/p&gt;
&lt;p&gt;As for any &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical test&lt;/a&gt;, if the &lt;strong&gt;&lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/#a-note-on-p-value-and-significance-level-alpha&#34;&gt;&lt;em&gt;p&lt;/em&gt;-value&lt;/a&gt; is less&lt;/strong&gt; than the chosen &lt;strong&gt;significance threshold&lt;/strong&gt; (generally &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;) then the null hypothesis is rejected and we will conclude that the &lt;strong&gt;lowest/highest value is an outlier&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;On the contrary, if the &lt;strong&gt;&lt;em&gt;p&lt;/em&gt;-value is greater or equal&lt;/strong&gt; than the significance level, the null hypothesis is not rejected, and we will conclude that, based on the data, we do not reject the hypothesis that the &lt;strong&gt;lowest/highest value is not an outlier&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Note that the Grubbs test is not appropriate for sample size of 6 or less (&lt;span class=&#34;math inline&#34;&gt;\(n \le 6\)&lt;/span&gt;).&lt;/p&gt;
&lt;p&gt;To perform the Grubbs test in R, we use the &lt;code&gt;grubbs.test()&lt;/code&gt; function from the &lt;code&gt;{outliers}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# install.packages(&amp;quot;outliers&amp;quot;)
library(outliers)

# Grubbs test
test &amp;lt;- grubbs.test(dat_tests)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Grubbs test for one outlier
## 
## data:  dat_tests
## G = 3.68326, U = 0.72325, p-value = 0.001873
## alternative hypothesis: highest value 5 is an outlier&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.002. At the 5% significance level, we reject the hypothesis that the &lt;em&gt;highest&lt;/em&gt; value 5 is &lt;strong&gt;not&lt;/strong&gt; an outlier. In other words, based on this test, we conclude that the highest value 5 is an outlier.&lt;/p&gt;
&lt;p&gt;By default, the test is performed on the highest value (as shown in the R output: &lt;code&gt;alternative hypothesis: highest value 5 is an outlier&lt;/code&gt;). If you want to do the test for the lowest value, simply add the argument &lt;code&gt;opposite = TRUE&lt;/code&gt; in the &lt;code&gt;grubbs.test()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- grubbs.test(dat_tests, opposite = TRUE)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Grubbs test for one outlier
## 
## data:  dat_tests
## G = 2.02893, U = 0.91602, p-value = 0.9981
## alternative hypothesis: lowest value -2.65645542090478 is an outlier&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The R output indicates that the test is now performed on the lowest value (see &lt;code&gt;alternative hypothesis: lowest value -2.6564554 is an outlier&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.998. At the 5% significance level, we do not reject the hypothesis that the &lt;em&gt;lowest&lt;/em&gt; value -2.66 is &lt;strong&gt;not&lt;/strong&gt; an outlier. In other words, we cannot conlude that the lowest value -2.66 is an outlier.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;dixons-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Dixon’s test&lt;/h2&gt;
&lt;p&gt;Similar to the Grubbs test, Dixon test is used to test whether a single low or high value is an outlier. So if more than one outliers is suspected, the test has to be performed on these suspected outliers individually.&lt;/p&gt;
&lt;p&gt;Note that Dixon test is most useful for small sample size (usually &lt;span class=&#34;math inline&#34;&gt;\(n \le 25\)&lt;/span&gt;).&lt;/p&gt;
&lt;p&gt;To perform the Dixon’s test in R, we use the &lt;code&gt;dixon.test()&lt;/code&gt; function from the &lt;code&gt;{outliers}&lt;/code&gt; package.&lt;/p&gt;
&lt;p&gt;For this illustration, as the Dixon test can only be done on small samples, we take a &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/#subset-a-data-frame&#34;&gt;subset&lt;/a&gt; of our simulated data which consists of the 20 first observations and the outlier. Note that R will throw an &lt;a href=&#34;https://statsandr.com/blog/top-10-errors-in-r/&#34;&gt;error&lt;/a&gt; and accepts only a dataset consisting of 3 to 30 observations for this test.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# subset of simulated data
subdat &amp;lt;- c(dat_tests[1:20], max(dat_tests))

# Dixon test
test &amp;lt;- dixon.test(subdat)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Dixon test for outliers
## 
## data:  subdat
## Q = 0.46668, p-value = 0.06429
## alternative hypothesis: highest value 5 is an outlier&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Results of the Dixon test show that we cannot conclude that the highest value 5 is an outlier (&lt;em&gt;p&lt;/em&gt;-value = 0.064).&lt;/p&gt;
&lt;p&gt;To test for the lowest value, simply add the &lt;code&gt;opposite = TRUE&lt;/code&gt; argument to the &lt;code&gt;dixon.test()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- dixon.test(subdat,
  opposite = TRUE
)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Dixon test for outliers
## 
## data:  subdat
## Q = 0.27115, p-value = 0.6872
## alternative hypothesis: lowest value -2.65645542090478 is an outlier&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Results of the test show that we cannot conclude that the lowest value -2.66 is an outlier (&lt;em&gt;p&lt;/em&gt;-value = 0.687).&lt;/p&gt;
&lt;p&gt;It is a good practice to always check the results of the statistical test for outliers against the boxplot to make sure we tested &lt;strong&gt;all&lt;/strong&gt; potential outliers:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;out &amp;lt;- boxplot.stats(subdat)$out

boxplot(subdat)
mtext(paste(&amp;quot;Outlier: &amp;quot;, paste(out, collapse = &amp;quot;, &amp;quot;)))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-08-11-outliers-detection-in-r_files/figure-html/unnamed-chunk-27-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;From the boxplot, we see that the Dixon test has been applied to all potential outliers.&lt;/p&gt;
&lt;p&gt;If you need to perform the test again without the highest or lowest value, this can be done by finding the row number of the maximum or minimum value, excluding this row number from the dataset and then finally apply the Dixon test on this new dataset. We illustrate the process as if we needed to perform the test again, but this time on the data excluding the highest value:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# find and exclude highest value
remove_ind &amp;lt;- which.max(subdat)
subsubdat &amp;lt;- subdat[-remove_ind]

# Dixon test on dataset without the maximum
test &amp;lt;- dixon.test(subsubdat)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Dixon test for outliers
## 
## data:  subsubdat
## Q = 0.30413, p-value = 0.5547
## alternative hypothesis: lowest value -2.65645542090478 is an outlier&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Results show that we cannot conclude that the lowest value -2.66 is an outlier (&lt;em&gt;p&lt;/em&gt;-value = 0.555).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;rosners-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Rosner’s test&lt;/h2&gt;
&lt;p&gt;Rosner’s test for outliers has the advantages that:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;it is used to &lt;strong&gt;detect several outliers at once&lt;/strong&gt; (unlike Grubbs and Dixon test which must be performed iteratively to screen for multiple outliers), and&lt;/li&gt;
&lt;li&gt;it is designed to avoid the problem of masking, where an outlier that is close in value to another outlier can go undetected.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Unlike Dixon test, note that Rosner test is most appropriate when the sample size is large (&lt;span class=&#34;math inline&#34;&gt;\(n \ge 20\)&lt;/span&gt;). We therefore use again the similated dataset (i.e., &lt;code&gt;dat_tests&lt;/code&gt;), which includes 51 observations.&lt;/p&gt;
&lt;p&gt;To perform the Rosner test, we use the &lt;code&gt;rosnerTest()&lt;/code&gt; function from the &lt;code&gt;{EnvStats}&lt;/code&gt; package. This function requires at least 2 arguments: the data and the number of suspected outliers &lt;code&gt;k&lt;/code&gt; (with &lt;code&gt;k = 3&lt;/code&gt; as the default number of suspected outliers).&lt;/p&gt;
&lt;p&gt;For this example, we set the number of suspected outliers to be equal to 1, as suggested by the number of potential outliers outlined in the boxplot.&lt;a href=&#34;#fn6&#34; class=&#34;footnote-ref&#34; id=&#34;fnref6&#34;&gt;&lt;sup&gt;6&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(EnvStats)

# Rosner test
test &amp;lt;- rosnerTest(dat_tests,
  k = 1
)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Results of Outlier Test
## -------------------------
## 
## Test Method:                     Rosner&amp;#39;s Test for Outliers
## 
## Hypothesized Distribution:       Normal
## 
## Data:                            dat_tests
## 
## Sample Size:                     51
## 
## Test Statistic:                  R.1 = 3.683258
## 
## Test Statistic Parameter:        k = 1
## 
## Alternative Hypothesis:          Up to 1 observations are not
##                                  from the same Distribution.
## 
## Type I Error:                    5%
## 
## Number of Outliers Detected:     1
## 
##   i     Mean.i     SD.i Value Obs.Num    R.i+1 lambda.i+1 Outlier
## 1 0 0.06306688 1.340371     5      51 3.683258   3.136165    TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The interesting results are provided in the &lt;code&gt;$all.stats&lt;/code&gt; table:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$all.stats&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   i     Mean.i     SD.i Value Obs.Num    R.i+1 lambda.i+1 Outlier
## 1 0 0.06306688 1.340371     5      51 3.683258   3.136165    TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Based on the results of the Rosner test, we see that there is only one outlier (as the table contains 1 line), and that it is the observation 51 (see &lt;code&gt;Obs.Num&lt;/code&gt;) with a value of 5 (see &lt;code&gt;Value&lt;/code&gt;). This finding aligns with the Grubbs test presented above, which also detected the value 5 as an outlier.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;additional-remarks&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Additional remarks&lt;/h1&gt;
&lt;p&gt;You will find many other methods to detect outliers:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;in the &lt;code&gt;{outliers}&lt;/code&gt; packages,&lt;/li&gt;
&lt;li&gt;via the &lt;code&gt;lofactor()&lt;/code&gt; function from the &lt;code&gt;{DMwR}&lt;/code&gt; package: Local Outlier Factor (LOF) is an algorithm used to identify outliers by comparing the local density of a point with that of its neighbors,&lt;/li&gt;
&lt;li&gt;the &lt;code&gt;outlierTest()&lt;/code&gt; from the &lt;code&gt;{car}&lt;/code&gt; package gives the most extreme observation based on the given model and allows to test whether it is an outlier,&lt;/li&gt;
&lt;li&gt;in the &lt;code&gt;{OutlierDetection}&lt;/code&gt; package, and&lt;/li&gt;
&lt;li&gt;with the &lt;code&gt;aq.plot()&lt;/code&gt; function from the &lt;code&gt;{mvoutlier}&lt;/code&gt; package (Thanks KTR for the suggestion.).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;We present these methods with the initial dataset &lt;code&gt;mpg&lt;/code&gt;, using the &lt;code&gt;cyl&lt;/code&gt; and &lt;code&gt;hwy&lt;/code&gt; variables:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(mvoutlier)

Y &amp;lt;- as.matrix(ggplot2::mpg[, c(&amp;quot;cyl&amp;quot;, &amp;quot;hwy&amp;quot;)])
res &amp;lt;- aq.plot(Y)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-08-11-outliers-detection-in-r_files/figure-html/unnamed-chunk-31-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Note also that some transformations may “naturally” eliminate outliers. The natural log or square root of a value reduces the variation caused by extreme values, so in some cases applying these transformations will help in making potential outliers less extreme.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to detect outliers in R via several descriptive statistics (including minimum, maximum, histogram, boxplot and percentiles) or thanks to more formal techniques of outliers detection (including Hampel filter, Grubbs, Dixon and Rosner tests).&lt;/p&gt;
&lt;p&gt;It is now your turn to try to detect outliers in your data, and decide how to treat them (i.e., keeping, removing or imputing them) before conducting your analyses.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;(Note that this article is available for download on my &lt;a href=&#34;https://statsandr.gumroad.com/&#34;&gt;Gumroad page&lt;/a&gt;.)&lt;/em&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-enderlein1987hawkins&#34; class=&#34;csl-entry&#34;&gt;
Enderlein, G. 1987. &lt;span&gt;“Hawkins, DM: Identification of Outliers. Chapman and Hall, London–New York 1980, 188 s.,&lt;span&gt;£&lt;/span&gt; 14, 50.”&lt;/span&gt; &lt;em&gt;Biometrical Journal&lt;/em&gt; 29 (2): 198–98.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;Thanks Felix Kluxen for the valuable suggestion.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Thanks to Victor for pointing out the &lt;code&gt;range()&lt;/code&gt; function.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;Thanks to Marlenildo for pointing out the &lt;code&gt;identify_outliers()&lt;/code&gt; function.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;The default is 3 (according to Pearson’s rule), but another value is also possible.&lt;a href=&#34;#fnref4&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn5&#34;&gt;&lt;p&gt;The constant in the &lt;code&gt;mad()&lt;/code&gt; function is 1.4826 by default, so it has to be set to 1 to find the median absolute deviation. See &lt;code&gt;help(mad)&lt;/code&gt; for more details. Thanks to Elisei for pointing this out to me.&lt;a href=&#34;#fnref5&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn6&#34;&gt;&lt;p&gt;In order to avoid flawed conclusions, it is important to pre-screen the data (graphically with a boxplot for example) to make the selection of the number of potential outliers as accurate as possible prior to running Rosner’s test.&lt;a href=&#34;#fnref6&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Wilcoxon test in R: how to compare 2 groups under the non-normality assumption?</title>
      <link>https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/</link>
      <pubDate>Sun, 07 Jun 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#two-different-scenarios&#34; id=&#34;toc-two-different-scenarios&#34;&gt;Two different scenarios&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#independent-samples&#34; id=&#34;toc-independent-samples&#34;&gt;Independent samples&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#paired-samples&#34; id=&#34;toc-paired-samples&#34;&gt;Paired samples&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#combination-of-plot-and-statistical-test&#34; id=&#34;toc-combination-of-plot-and-statistical-test&#34;&gt;Combination of plot and statistical test&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#independent-samples-1&#34; id=&#34;toc-independent-samples-1&#34;&gt;Independent samples&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#paired-samples-1&#34; id=&#34;toc-paired-samples-1&#34;&gt;Paired samples&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#assumption-of-equal-variances&#34; id=&#34;toc-assumption-of-equal-variances&#34;&gt;Assumption of equal variances&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-06-07-wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption_files/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;In a previous article, we showed how to &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;compare two groups under different scenarios using the Student’s t-test&lt;/a&gt;. The Student’s t-test requires that the distributions follow a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution&lt;/a&gt; when in presence of small samples.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In this article, we show how to &lt;strong&gt;compare two groups when the normality assumption is violated&lt;/strong&gt;, using the &lt;strong&gt;Wilcoxon test&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The Wilcoxon test is a &lt;strong&gt;non-parametric test&lt;/strong&gt;, meaning that it does not rely on data belonging to any particular parametric family of probability distributions. Non-parametric tests have the same objective as their parametric counterparts. However, they have two advantages over parametric tests: they &lt;strong&gt;do not require the assumption of normality&lt;/strong&gt; of distributions and they can deal with &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;A Student’s t-test for instance is only applicable if the data are Gaussian or if the sample size is large enough (usually &lt;span class=&#34;math inline&#34;&gt;\(n \ge 30\)&lt;/span&gt;, thanks to the central limit theorem). A non-parametric test should be used in other cases.&lt;/p&gt;
&lt;p&gt;One may wonder why we would not always use a non-parametric test so we do not have to bother about testing for normality. The reason is that non-parametric tests are usually less powerful than corresponding parametric tests when the normality assumption holds.&lt;/p&gt;
&lt;p&gt;Therefore, all else being equal, with a non-parametric test you are less likely to reject the &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/#step-1-stating-the-null-and-alternative-hypothesis&#34;&gt;null hypothesis&lt;/a&gt; when it is false if the data follows a normal distribution. It is thus preferred to use the parametric version of a &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical test&lt;/a&gt; when the assumptions are met.&lt;/p&gt;
&lt;p&gt;In the remaining of the article, we present the two scenarios of the Wilcoxon test and how to perform them in R through two examples.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;two-different-scenarios&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Two different scenarios&lt;/h1&gt;
&lt;p&gt;As for the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test&lt;/a&gt;, the Wilcoxon test is used to compare two groups and see whether they are significantly different from each other in terms of the variable of interest.&lt;/p&gt;
&lt;p&gt;The two groups to be compared are either:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;independent, or&lt;/li&gt;
&lt;li&gt;paired (i.e., dependent)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;There are actually two versions of the Wilcoxon test:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;The &lt;strong&gt;Mann-Whitney-Wilcoxon&lt;/strong&gt; test (also referred as Wilcoxon rank sum test or Mann-Whitney U test) is performed when the samples are &lt;strong&gt;independent&lt;/strong&gt; (so this test is the non-parametric equivalent to the Student’s t-test for independent samples).&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;Wilcoxon signed-rank&lt;/strong&gt; test (also sometimes referred as Wilcoxon test for paired samples) is performed when the samples are &lt;strong&gt;paired/dependent&lt;/strong&gt; (so this test is the non-parametric equivalent to the Student’s t-test for paired samples).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Luckily, those two tests can be done in R with the same function: &lt;code&gt;wilcox.test()&lt;/code&gt;. They are presented in the following sections.&lt;/p&gt;
&lt;div id=&#34;independent-samples&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Independent samples&lt;/h2&gt;
&lt;p&gt;For the Wilcoxon test with independent samples, suppose that we want to test whether grades at the statistics exam differ between female and male students.&lt;/p&gt;
&lt;p&gt;We have collected grades for 24 students (12 girls and 12 boys):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- data.frame(
  Sex = as.factor(c(rep(&amp;quot;Girl&amp;quot;, 12), rep(&amp;quot;Boy&amp;quot;, 12))),
  Grade = c(
    19, 18, 9, 17, 8, 7, 16, 19, 20, 9, 11, 18,
    16, 5, 15, 2, 14, 15, 4, 7, 15, 6, 7, 14
  )
)

dat&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##     Sex Grade
## 1  Girl    19
## 2  Girl    18
## 3  Girl     9
## 4  Girl    17
## 5  Girl     8
## 6  Girl     7
## 7  Girl    16
## 8  Girl    19
## 9  Girl    20
## 10 Girl     9
## 11 Girl    11
## 12 Girl    18
## 13  Boy    16
## 14  Boy     5
## 15  Boy    15
## 16  Boy     2
## 17  Boy    14
## 18  Boy    15
## 19  Boy     4
## 20  Boy     7
## 21  Boy    15
## 22  Boy     6
## 23  Boy     7
## 24  Boy    14&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here are the distributions of the grades by sex (using &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;&lt;code&gt;{ggplot2}&lt;/code&gt;&lt;/a&gt;):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggplot2)

ggplot(dat) +
  aes(x = Sex, y = Grade) +
  geom_boxplot(fill = &amp;quot;#0c4c8a&amp;quot;) +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-06-07-wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption_files/figure-html/unnamed-chunk-2-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;We first check whether the 2 samples follow a normal distribution via a histogram and the Shapiro-Wilk test:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;hist(subset(dat, Sex == &amp;quot;Girl&amp;quot;)$Grade,
  main = &amp;quot;Grades for girls&amp;quot;,
  xlab = &amp;quot;Grades&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-06-07-wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption_files/figure-html/unnamed-chunk-3-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;hist(subset(dat, Sex == &amp;quot;Boy&amp;quot;)$Grade,
  main = &amp;quot;Grades for boys&amp;quot;,
  xlab = &amp;quot;Grades&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-06-07-wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption_files/figure-html/unnamed-chunk-3-2.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;shapiro.test(subset(dat, Sex == &amp;quot;Girl&amp;quot;)$Grade)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Shapiro-Wilk normality test
## 
## data:  subset(dat, Sex == &amp;quot;Girl&amp;quot;)$Grade
## W = 0.84548, p-value = 0.0323&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;shapiro.test(subset(dat, Sex == &amp;quot;Boy&amp;quot;)$Grade)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Shapiro-Wilk normality test
## 
## data:  subset(dat, Sex == &amp;quot;Boy&amp;quot;)$Grade
## W = 0.84313, p-value = 0.03023&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The histograms show that both distributions do not seem to follow a normal distribution and the &lt;em&gt;p&lt;/em&gt;-values of the Shapiro-Wilk tests confirm it (since we reject the null hypothesis of normality for both distributions at the 5% significance level).&lt;/p&gt;
&lt;p&gt;We just showed that normality assumption is violated for both groups so it is now time to see how to perform the Wilcoxon test in R.&lt;/p&gt;
&lt;p&gt;Note that in order to use the Student’s t-test (the parametric version of the Wilcoxon test), it is required that &lt;strong&gt;both samples follow a normal distribution&lt;/strong&gt; if samples are small.&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt; Therefore, even if one sample follows a normal distribution (and the other does not follow a normal distribution), it is recommended to use the non-parametric test.&lt;/p&gt;
&lt;p&gt;Remember that the null and alternative hypothesis of the Wilcoxon test are as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: the 2 groups are equal in terms of the variable of interest&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: the 2 groups are different in terms of the variable of interest&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Applied to our research question, we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: grades of girls and boys are equal&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: grades of girls and boys are different&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- wilcox.test(dat$Grade ~ dat$Sex)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Wilcoxon rank sum test with continuity correction
## 
## data:  dat$Grade by dat$Sex
## W = 31.5, p-value = 0.02056
## alternative hypothesis: true location shift is not equal to 0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We obtain the test statistic, the &lt;em&gt;p&lt;/em&gt;-value and a reminder of the hypothesis tested.&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.021. Therefore, at the 5% significance level, we reject the null hypothesis and we conclude that grades are significantly different between girls and boys.&lt;/p&gt;
&lt;p&gt;Given the boxplot presented above showing the grades by sex, one may see that girls seem to perform better than boys. This can be tested formally by adding the &lt;code&gt;alternative = &#34;less&#34;&lt;/code&gt; argument to the &lt;code&gt;wilcox.test()&lt;/code&gt; function:&lt;a href=&#34;#fn4&#34; class=&#34;footnote-ref&#34; id=&#34;fnref4&#34;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- wilcox.test(dat$Grade ~ dat$Sex,
  alternative = &amp;quot;less&amp;quot;
)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Wilcoxon rank sum test with continuity correction
## 
## data:  dat$Grade by dat$Sex
## W = 31.5, p-value = 0.01028
## alternative hypothesis: true location shift is less than 0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.01. Therefore, at the 5% significance level, we reject the null hypothesis and we conclude that boys performed significantly worse than girls (which is equivalent than concluding that girls performed significantly better than boys).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;paired-samples&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Paired samples&lt;/h2&gt;
&lt;p&gt;For this second scenario, consider that we administered a math test in a class of 12 students at the beginning of a semester, and that we administered a similar test at the end of the semester to the exact same students. We have the following data:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat2 &amp;lt;- data.frame(
  Beginning = c(16, 5, 15, 2, 14, 15, 4, 7, 15, 6, 7, 14),
  End = c(19, 18, 9, 17, 8, 7, 16, 19, 20, 9, 11, 18)
)

dat2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    Beginning End
## 1         16  19
## 2          5  18
## 3         15   9
## 4          2  17
## 5         14   8
## 6         15   7
## 7          4  16
## 8          7  19
## 9         15  20
## 10         6   9
## 11         7  11
## 12        14  18&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We transform the dataset to have it in a &lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/#introduction&#34;&gt;tidy format&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat2 &amp;lt;- data.frame(
  Time = c(rep(&amp;quot;Before&amp;quot;, 12), rep(&amp;quot;After&amp;quot;, 12)),
  Grade = c(dat2$Beginning, dat2$End)
)
dat2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      Time Grade
## 1  Before    16
## 2  Before     5
## 3  Before    15
## 4  Before     2
## 5  Before    14
## 6  Before    15
## 7  Before     4
## 8  Before     7
## 9  Before    15
## 10 Before     6
## 11 Before     7
## 12 Before    14
## 13  After    19
## 14  After    18
## 15  After     9
## 16  After    17
## 17  After     8
## 18  After     7
## 19  After    16
## 20  After    19
## 21  After    20
## 22  After     9
## 23  After    11
## 24  After    18&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The distribution of the grades at the beginning and after the semester:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Reordering dat2$Time
dat2$Time &amp;lt;- factor(dat2$Time,
  levels = c(&amp;quot;Before&amp;quot;, &amp;quot;After&amp;quot;)
)

ggplot(dat2) +
  aes(x = Time, y = Grade) +
  geom_boxplot(fill = &amp;quot;#0c4c8a&amp;quot;) +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-06-07-wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption_files/figure-html/unnamed-chunk-8-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;(See the &lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/&#34;&gt;&lt;code&gt;{esquisse}&lt;/code&gt; and &lt;code&gt;{questionr}&lt;/code&gt; addins&lt;/a&gt; to help you reorder levels of a factor variable and to easily draw plots with the &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;&lt;code&gt;{ggplot2}&lt;/code&gt; package&lt;/a&gt;.)&lt;/p&gt;
&lt;p&gt;In this example, it is clear that the two samples are not independent since the same 12 students took the exam before and after the semester. Supposing also that the normality assumption is violated (and given the small sample size), we thus use the Wilcoxon test for &lt;strong&gt;paired samples&lt;/strong&gt;, with the following hypotheses:&lt;a href=&#34;#fn5&#34; class=&#34;footnote-ref&#34; id=&#34;fnref5&#34;&gt;&lt;sup&gt;5&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: grades before and after the semester are equal&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: grades before and after the semester are different&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We add the &lt;code&gt;paired = TRUE&lt;/code&gt; argument to the &lt;code&gt;wilcox.test()&lt;/code&gt; function to take into consideration the dependency between the 2 samples:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;before &amp;lt;- dat2$Grade[dat2$Time == &amp;quot;Before&amp;quot;]
after &amp;lt;- dat2$Grade[dat2$Time == &amp;quot;After&amp;quot;]
test &amp;lt;- wilcox.test(before, after, paired = TRUE)

test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Wilcoxon signed rank test with continuity correction
## 
## data:  before and after
## V = 21, p-value = 0.1692
## alternative hypothesis: true location shift is not equal to 0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We obtain the test statistic, the &lt;em&gt;p&lt;/em&gt;-value and a reminder of the hypothesis tested.&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.169. Therefore, at the 5% significance level, we do not reject the null hypothesis that the grades are similar before and after the semester.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;combination-of-plot-and-statistical-test&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Combination of plot and statistical test&lt;/h1&gt;
&lt;p&gt;After having written this article, I discovered the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package which I believe is worth mentioning here, in particular the &lt;code&gt;ggbetweenstats()&lt;/code&gt; and &lt;code&gt;ggwithinstats()&lt;/code&gt; functions for independent and paired samples, respectively.&lt;/p&gt;
&lt;p&gt;These two functions combine a boxplot—representing the distribution for each group—and the results of the statistical test displayed in the subtitle of the plot.&lt;/p&gt;
&lt;p&gt;See examples below for independent and paired samples, using the same data than previously.&lt;/p&gt;
&lt;div id=&#34;independent-samples-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Independent samples&lt;/h2&gt;
&lt;p&gt;For independent samples, it is the &lt;code&gt;ggbetweenstats()&lt;/code&gt; function which is used:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load package
library(ggstatsplot)

# plot with statistical results
ggbetweenstats( # independent samples
  data = dat,
  x = Sex,
  y = Grade,
  plot.type = &amp;quot;box&amp;quot;, # for boxplot
  type = &amp;quot;nonparametric&amp;quot;, # for wilcoxon
  centrality.plotting = FALSE # remove median
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-06-07-wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption_files/figure-html/unnamed-chunk-10-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value (displayed after &lt;code&gt;p =&lt;/code&gt; in the subtitle of the plot) indicates that we reject the null hypothesis, and we conclude that grades are significantly different between girls and boys (&lt;em&gt;p&lt;/em&gt;-value = 0.02).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;paired-samples-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Paired samples&lt;/h2&gt;
&lt;p&gt;For paired samples, it is the &lt;code&gt;ggwithinstats()&lt;/code&gt; function which is used:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load package
library(ggstatsplot)

# plot with statistical results
ggwithinstats( # paired samples
  data = dat2,
  x = Time,
  y = Grade,
  type = &amp;quot;nonparametric&amp;quot;, # for wilcoxon
  centrality.plotting = FALSE # remove median
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-06-07-wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption_files/figure-html/unnamed-chunk-11-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value (displayed after &lt;code&gt;p =&lt;/code&gt; in the subtitle of the plot) indicates that we do not reject the null hypothesis, so we do not reject the hypothesis that grades are equal before and after the semester (&lt;em&gt;p&lt;/em&gt;-value = 0.17).&lt;/p&gt;
&lt;p&gt;The point of this section was to illustrate how to easily draw plots together with statistical results, which is exactly the aim of the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package. See more details and examples in this &lt;a href=&#34;https://statsandr.com/blog/how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way/&#34;&gt;article&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;assumption-of-equal-variances&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Assumption of equal variances&lt;/h1&gt;
&lt;p&gt;As written at the beginning of the article, the Wilcoxon test does not require the assumption of normality in case of small samples.&lt;/p&gt;
&lt;p&gt;Regarding the assumption of equal variances, this assumption may or may not be needed depending on your goal. If you only want to compare the two groups, you do not have to test the equality of variances because the two distributions do not have to have the same shape. However, if your goal is to &lt;strong&gt;compare medians of the two groups&lt;/strong&gt;, then you will need to make sure that the two distributions have the same shape (and thus, the same variance).&lt;a href=&#34;#fn6&#34; class=&#34;footnote-ref&#34; id=&#34;fnref6&#34;&gt;&lt;sup&gt;6&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;So results of your test of equality of variances will change your interpretation: differences in the “distributions” of two groups or differences in the “medians” of two groups.&lt;/p&gt;
&lt;p&gt;In this article I do not wish to compare medians, I only want compare the groups by determining whether there are differences in the distributions of the two groups. This is the reason I do not test for equality of variances.&lt;/p&gt;
&lt;p&gt;Note that this is equivalent when performing the &lt;a href=&#34;https://statsandr.com/blog/kruskal-wallis-test-nonparametric-version-anova/&#34;&gt;Kruskal-Wallis test&lt;/a&gt; to compare three groups or more (i.e., the non-parametric version of the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;ANOVA&lt;/a&gt;): if you only want to test whether there are differences in the groups you do not need homoscedasticity, whereas if you want to compare the medians this assumption must be met.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to compare two groups that do not follow a normal distribution in R using the Wilcoxon test. See also:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the &lt;a href=&#34;https://statsandr.com/blog/one-sample-wilcoxon-test-in-r/&#34;&gt;one-sample Wilcoxon test&lt;/a&gt; if you have only one group and want to compare it to a default given value,&lt;/li&gt;
&lt;li&gt;the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test&lt;/a&gt; if you need to perform the parametric version of the two-sample Wilcoxon test,&lt;/li&gt;
&lt;li&gt;and the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;ANOVA&lt;/a&gt; if you need to compare 3 groups or more.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-stevens2013intermediate&#34; class=&#34;csl-entry&#34;&gt;
Stevens, James P. 2013. &lt;em&gt;Intermediate Statistics: A Modern Approach&lt;/em&gt;. Routledge.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;Remember that the normality assumption can be tested via 3 complementary methods: (i) histogram, (ii) QQ-plot and (iii) normality tests (with the most common being the Shapiro-Wilk test). See &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;how to determine if a distribution follows a normal distribution&lt;/a&gt; if you need a refresh.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;In case of large samples, &lt;strong&gt;normality is not required&lt;/strong&gt; (this is a common misconception!). By the &lt;a href=&#34;https://en.wikipedia.org/wiki/Central_limit_theorem&#34; target=&#34;_blank&#34;&gt;central limit theorem&lt;/a&gt;, sample means of large samples are often well-approximated by a normal distribution even if the data are not normally distributed &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-stevens2013intermediate&#34;&gt;Stevens 2013&lt;/a&gt;)&lt;/span&gt;.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;Note that the presence of equal elements (ties) prevents an exact &lt;em&gt;p&lt;/em&gt;-value calculation. This can be tackled by computing the exact or asymptotic Wilcoxon-Mann-Whitney test with adjustment for ties, using the &lt;code&gt;wilcox_test()&lt;/code&gt; function from the &lt;code&gt;{coin}&lt;/code&gt; package: &lt;code&gt;wilcox_test(dat$Grade ~ dat$Sex, distribution = exact())&lt;/code&gt; or &lt;code&gt;wilcox_test(dat$Grade ~ dat$Sex)&lt;/code&gt;. In our case, conclusions remain unchanged.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;We add &lt;code&gt;alternative = &#34;less&#34;&lt;/code&gt; (and not &lt;code&gt;alternative = &#34;greater&#34;&lt;/code&gt;) because we want to test that grades for boys are &lt;strong&gt;less&lt;/strong&gt; than grade for girls. Using &lt;code&gt;&#34;less&#34;&lt;/code&gt; or &lt;code&gt;&#34;greater&#34;&lt;/code&gt; can be deducted from the reference level in the dataset.&lt;a href=&#34;#fnref4&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn5&#34;&gt;&lt;p&gt;Note that for paired samples (when in presence of a small sample), normality must be checked on the &lt;em&gt;differences&lt;/em&gt; between the two paired samples, and not individually on the two samples like it is done for independent samples.&lt;a href=&#34;#fnref5&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn6&#34;&gt;&lt;p&gt;See these three articles for a more detailed discussion on the assumption of equal variances in Wilcoxon test: &lt;a href=&#34;https://statistics.laerd.com/statistical-guides/mann-whitney-u-test-assumptions.php&#34;&gt;1&lt;/a&gt;, &lt;a href=&#34;https://influentialpoints.com/Training/Wilcoxon-Mann-Whitney_U_test_use_and_misuse.htm&#34;&gt;2&lt;/a&gt; &amp;amp; &lt;a href=&#34;https://influentialpoints.com/Training/Wilcoxon_matched_pairs_signed_rank_test_use_and_misuse.htm&#34;&gt;3&lt;/a&gt;.&lt;a href=&#34;#fnref6&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Correlation coefficient and correlation test in R</title>
      <link>https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/</link>
      <pubDate>Thu, 28 May 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#data&#34; id=&#34;toc-data&#34;&gt;Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#correlation-coefficient&#34; id=&#34;toc-correlation-coefficient&#34;&gt;Correlation coefficient&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#between-two-variables&#34; id=&#34;toc-between-two-variables&#34;&gt;Between two variables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#correlation-matrix-correlations-for-all-variables&#34; id=&#34;toc-correlation-matrix-correlations-for-all-variables&#34;&gt;Correlation matrix: correlations for all variables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#interpretation-of-a-correlation-coefficient&#34; id=&#34;toc-interpretation-of-a-correlation-coefficient&#34;&gt;Interpretation of a correlation coefficient&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#visualizations&#34; id=&#34;toc-visualizations&#34;&gt;Visualizations&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#a-scatterplot-for-2-variables&#34; id=&#34;toc-a-scatterplot-for-2-variables&#34;&gt;A scatterplot for 2 variables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scatterplots-for-several-pairs-of-variables&#34; id=&#34;toc-scatterplots-for-several-pairs-of-variables&#34;&gt;Scatterplots for several pairs of variables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#another-simple-correlation-matrix&#34; id=&#34;toc-another-simple-correlation-matrix&#34;&gt;Another simple correlation matrix&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#correlation-test&#34; id=&#34;toc-correlation-test&#34;&gt;Correlation test&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#for-2-variables&#34; id=&#34;toc-for-2-variables&#34;&gt;For 2 variables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#for-several-pairs-of-variables&#34; id=&#34;toc-for-several-pairs-of-variables&#34;&gt;For several pairs of variables&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#combination-of-correlation-coefficients-and-correlation-tests&#34; id=&#34;toc-combination-of-correlation-coefficients-and-correlation-tests&#34;&gt;Combination of correlation coefficients and correlation tests&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#correlograms&#34; id=&#34;toc-correlograms&#34;&gt;Correlograms&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#correlation-does-not-imply-causation&#34; id=&#34;toc-correlation-does-not-imply-causation&#34;&gt;Correlation does not imply causation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-28-correlation-coefficient-and-correlation-test-in-r_files/correlation-coefficient-and-correlation-test-in-r.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;Correlations between variables play an important role in a &lt;a href=&#34;https://statsandr.com/tags/descriptive-statistics/&#34;&gt;descriptive analysis&lt;/a&gt;. A correlation measures the &lt;strong&gt;relationship between two variables&lt;/strong&gt;, that is, how they are linked to each other. In this sense, a correlation allows to know which variables evolve in the same direction, which ones evolve in the opposite direction, and which ones are independent.&lt;/p&gt;
&lt;p&gt;In this article, I show how to compute &lt;strong&gt;correlation coefficients&lt;/strong&gt;, how to perform &lt;strong&gt;correlation tests&lt;/strong&gt; and how to &lt;strong&gt;visualize relationships&lt;/strong&gt; between variables in R.&lt;/p&gt;
&lt;p&gt;Correlation is usually computed on two &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#quantitative&#34;&gt;quantitative&lt;/a&gt; variables, but it can also be computed on two &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#ordinal&#34;&gt;qualitative ordinal&lt;/a&gt; variables.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; See the &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;Chi-square test of independence&lt;/a&gt; if you need to study the relationship between two &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#nominal&#34;&gt;qualitative nominal&lt;/a&gt; variables.&lt;/p&gt;
&lt;p&gt;If you need to &lt;em&gt;quantify&lt;/em&gt; the relationship between two variables, I refer you to the article about &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;linear regression&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;data&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Data&lt;/h1&gt;
&lt;p&gt;In this article, we use the &lt;code&gt;mtcars&lt;/code&gt; dataset (loaded by default in R):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# display first 5 observations
head(mtcars, 5)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The variables &lt;code&gt;vs&lt;/code&gt; and &lt;code&gt;am&lt;/code&gt; are categorical variables, so they are removed for this article:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# remove vs and am variables
library(tidyverse)
dat &amp;lt;- mtcars %&amp;gt;%
  select(-vs, -am)

# display 5 first obs. of new dataset
head(dat, 5)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##                    mpg cyl disp  hp drat    wt  qsec gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02    3    2&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;correlation-coefficient&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Correlation coefficient&lt;/h1&gt;
&lt;div id=&#34;between-two-variables&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Between two variables&lt;/h2&gt;
&lt;p&gt;The correlation between 2 variables is found with the &lt;code&gt;cor()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;Suppose we want to compute the correlation between horsepower (&lt;code&gt;hp&lt;/code&gt;) and miles per gallon (&lt;code&gt;mpg&lt;/code&gt;):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Pearson correlation between 2 variables
cor(dat$hp, dat$mpg)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] -0.7761684&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the correlation between variables &lt;em&gt;X&lt;/em&gt; and &lt;em&gt;Y&lt;/em&gt; is equal to the correlation between variables &lt;em&gt;Y&lt;/em&gt; and &lt;em&gt;X&lt;/em&gt; so the order of the variables in the &lt;code&gt;cor()&lt;/code&gt; function does not matter.&lt;/p&gt;
&lt;p&gt;The Pearson correlation is computed by default with the &lt;code&gt;cor()&lt;/code&gt; function. If you want to compute the Spearman correlation, add the argument &lt;code&gt;method = &#34;spearman&#34;&lt;/code&gt; to the &lt;code&gt;cor()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Spearman correlation between 2 variables
cor(dat$hp, dat$mpg,
  method = &amp;quot;spearman&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] -0.8946646&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The most common correlation methods (Run &lt;code&gt;?cor&lt;/code&gt; for more information about the different methods available in the &lt;code&gt;cor()&lt;/code&gt; function) are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Pearson&lt;/strong&gt; correlation is often used for &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#continuous&#34;&gt;quantitative continuous&lt;/a&gt; variables that have a linear relationship&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Spearman&lt;/strong&gt; correlation (which is actually similar to Pearson but based on the ranked values for each variable rather than on the raw data) is often used to evaluate relationships involving at least one &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#ordinal&#34;&gt;qualitative ordinal&lt;/a&gt; variable or two quantitative variables if the link is partially linear&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Kendall’s tau-b&lt;/strong&gt; which is computed from the number of concordant and discordant pairs is often used for qualitative ordinal variables&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that there exists the &lt;em&gt;point-biserial correlation&lt;/em&gt; (which can be used to measure the association between a continuous variable and a nominal variable of two levels), but this correlation is not covered here.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;correlation-matrix-correlations-for-all-variables&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Correlation matrix: correlations for all variables&lt;/h2&gt;
&lt;p&gt;Suppose now that we want to compute correlations for several pairs of variables. We can easily do so for all possible pairs of variables in the dataset, again with the &lt;code&gt;cor()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# correlation for all variables
round(cor(dat),
  digits = 2 # rounded to 2 decimals
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##        mpg   cyl  disp    hp  drat    wt  qsec  gear  carb
## mpg   1.00 -0.85 -0.85 -0.78  0.68 -0.87  0.42  0.48 -0.55
## cyl  -0.85  1.00  0.90  0.83 -0.70  0.78 -0.59 -0.49  0.53
## disp -0.85  0.90  1.00  0.79 -0.71  0.89 -0.43 -0.56  0.39
## hp   -0.78  0.83  0.79  1.00 -0.45  0.66 -0.71 -0.13  0.75
## drat  0.68 -0.70 -0.71 -0.45  1.00 -0.71  0.09  0.70 -0.09
## wt   -0.87  0.78  0.89  0.66 -0.71  1.00 -0.17 -0.58  0.43
## qsec  0.42 -0.59 -0.43 -0.71  0.09 -0.17  1.00 -0.21 -0.66
## gear  0.48 -0.49 -0.56 -0.13  0.70 -0.58 -0.21  1.00  0.27
## carb -0.55  0.53  0.39  0.75 -0.09  0.43 -0.66  0.27  1.00&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This correlation matrix gives an overview of the correlations for all combinations of two variables.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;interpretation-of-a-correlation-coefficient&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Interpretation of a correlation coefficient&lt;/h2&gt;
&lt;p&gt;First of all, correlation ranges from &lt;strong&gt;-1 to 1&lt;/strong&gt;. It gives us an indication on two things:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;The direction of the relationship between the 2 variables&lt;/li&gt;
&lt;li&gt;The strength of the relationship between the 2 variables&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Regarding the direction of the relationship: On the one hand, a &lt;strong&gt;negative correlation&lt;/strong&gt; implies that the two variables under consideration vary in &lt;strong&gt;opposite directions&lt;/strong&gt;, that is, if a variable increases the other decreases and vice versa. On the other hand, a &lt;strong&gt;positive correlation&lt;/strong&gt; implies that the two variables under consideration vary in the &lt;strong&gt;same direction&lt;/strong&gt;, i.e., if a variable increases the other one increases and if one decreases the other one decreases as well.&lt;/p&gt;
&lt;p&gt;Regarding the strength of the relationship: The &lt;strong&gt;more extreme&lt;/strong&gt; the correlation coefficient (the closer to -1 or 1), the &lt;strong&gt;stronger the relationship&lt;/strong&gt;. This also means that a &lt;strong&gt;correlation close to 0&lt;/strong&gt; indicates that the two variables are &lt;strong&gt;independent&lt;/strong&gt;, that is, as one variable increases, there is no tendency in the other variable to either decrease or increase.&lt;/p&gt;
&lt;p&gt;As an illustration, the Pearson correlation between horsepower (&lt;code&gt;hp&lt;/code&gt;) and miles per gallon (&lt;code&gt;mpg&lt;/code&gt;) found above is -0.78, meaning that the 2 variables vary in opposite direction. This makes sense, cars with more horsepower tend to consume more fuel (and thus have a lower mileage per gallon). On the contrary, from the correlation matrix we see that the correlation between miles per gallon (&lt;code&gt;mpg&lt;/code&gt;) and the time to drive 1/4 of a mile (&lt;code&gt;qsec&lt;/code&gt;) is 0.42, meaning that fast cars (low &lt;code&gt;qsec&lt;/code&gt;) tend to have a worse mileage per gallon (low &lt;code&gt;mpg&lt;/code&gt;). This again makes sense as fast cars tend to consume more fuel.&lt;/p&gt;
&lt;p&gt;Note that it is a good practice to visualize the type of the relationship between the two variables &lt;em&gt;before&lt;/em&gt; interpreting the correlation coefficients. The reason is that the correlation coefficient could be biased due to an &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outlier&lt;/a&gt; or due to the type of link between the two variables.&lt;/p&gt;
&lt;p&gt;For instance, see the two Pearson correlation coefficients (denoted by &lt;code&gt;R&lt;/code&gt; in the following plots) when the outlier is excluded and included:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-28-correlation-coefficient-and-correlation-test-in-r_files/figure-html/unnamed-chunk-6-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The Pearson correlation coefficient changes drastically due to a single point, and thus the interpretation. It goes from a negative correlation coefficient, indicating a negative relationship between the 2 variables, to a positive coefficient, indicating a positive relationship. We would have missed this insight if we had not visualized the data in a scatterplot (see how to draw a scatterplot in this &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/#visualizations&#34;&gt;section&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;A correlation coefficient may also miss a non-linear link between two variables:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-28-correlation-coefficient-and-correlation-test-in-r_files/figure-html/unnamed-chunk-7-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The Pearson correlation coefficient is equal to 0, indicating no relationship between the two variables, because it measures the &lt;strong&gt;linear&lt;/strong&gt; relationship and it is clear from the plot that the link is non-linear.&lt;/p&gt;
&lt;p&gt;So to recap, it is a good practice to visualize the data via a scatterplot before interpreting a correlation coefficient (it does not tell the whole story) and see how the correlation coefficient changes when using the parametric (Pearson) or nonparametric version (Spearman or Kendall’s tau-b).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;visualizations&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Visualizations&lt;/h1&gt;
&lt;p&gt;The correlation matrix presented above is not easily interpretable, especially when the dataset is composed of many variables. In the following sections, we present some alternatives to the correlation matrix for better readability.&lt;/p&gt;
&lt;div id=&#34;a-scatterplot-for-2-variables&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;A scatterplot for 2 variables&lt;/h2&gt;
&lt;p&gt;A good way to visualize a correlation between 2 variables is to draw a scatterplot of the two variables of interest. Suppose we want to examine the relationship between horsepower (&lt;code&gt;hp&lt;/code&gt;) and miles per gallon (&lt;code&gt;mpg&lt;/code&gt;):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# scatterplot
library(ggplot2)

ggplot(dat) +
  aes(x = hp, y = mpg) +
  geom_point(colour = &amp;quot;#0c4c8a&amp;quot;) +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-28-correlation-coefficient-and-correlation-test-in-r_files/figure-html/unnamed-chunk-8-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;If you are unfamiliar with the &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;&lt;code&gt;{ggplot2}&lt;/code&gt; package&lt;/a&gt;, you can draw the scatterplot using the &lt;code&gt;plot()&lt;/code&gt; function from R base graphics:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(dat$hp, dat$mpg)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-28-correlation-coefficient-and-correlation-test-in-r_files/figure-html/unnamed-chunk-9-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;or use the &lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#esquisse&#34;&gt;esquisse addin&lt;/a&gt; to easily draw plots using the &lt;code&gt;{ggplot2}&lt;/code&gt; package.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;scatterplots-for-several-pairs-of-variables&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scatterplots for several pairs of variables&lt;/h2&gt;
&lt;p&gt;Suppose that instead of visualizing the relationship between only 2 variables, we want to visualize the relationship for several pairs of variables. This is possible thanks to the &lt;code&gt;pair()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;For this illustration, we focus only on miles per gallon (&lt;code&gt;mpg&lt;/code&gt;), horsepower (&lt;code&gt;hp&lt;/code&gt;) and weight (&lt;code&gt;wt&lt;/code&gt;):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# multiple scatterplots
pairs(dat[, c(&amp;quot;mpg&amp;quot;, &amp;quot;hp&amp;quot;, &amp;quot;wt&amp;quot;)])&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-28-correlation-coefficient-and-correlation-test-in-r_files/figure-html/unnamed-chunk-10-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The figure indicates that weight (&lt;code&gt;wt&lt;/code&gt;) and horsepower (&lt;code&gt;hp&lt;/code&gt;) are positively correlated, whereas miles per gallon (&lt;code&gt;mpg&lt;/code&gt;) seems to be negatively correlated with horsepower (&lt;code&gt;hp&lt;/code&gt;) and weight (&lt;code&gt;wt&lt;/code&gt;).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;another-simple-correlation-matrix&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Another simple correlation matrix&lt;/h2&gt;
&lt;p&gt;This version of the correlation matrix presents the correlation coefficients in a slightly more readable way, i.e., by coloring the coefficients based on their sign. Applied to our dataset, we have:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# improved correlation matrix
library(corrplot)

corrplot(cor(dat),
  method = &amp;quot;number&amp;quot;,
  type = &amp;quot;upper&amp;quot; # show only upper side
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-28-correlation-coefficient-and-correlation-test-in-r_files/figure-html/unnamed-chunk-11-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;correlation-test&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Correlation test&lt;/h1&gt;
&lt;div id=&#34;for-2-variables&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;For 2 variables&lt;/h2&gt;
&lt;p&gt;Unlike a correlation matrix which indicates the correlation coefficients between some pairs of variables in the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;sample&lt;/a&gt;, a correlation test is used to test whether the correlation (denoted &lt;span class=&#34;math inline&#34;&gt;\(\rho\)&lt;/span&gt;) between 2 variables is significantly different from 0 or not in the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;population&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Actually, a correlation coefficient different from 0 in the sample does not mean that the correlation is &lt;strong&gt;significantly&lt;/strong&gt; different from 0 in the population. This needs to be tested with a &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis test&lt;/a&gt;—and known as the correlation test.&lt;/p&gt;
&lt;p&gt;The null and alternative hypothesis for the correlation test are as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\rho = 0\)&lt;/span&gt; (meaning that there is no linear relationship between the two variables)&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\rho \ne 0\)&lt;/span&gt; (meaning that there is a linear relationship between the two variables)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Via this correlation test, what we are actually testing is whether:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the sample contains sufficient evidence to reject the null hypothesis and conclude that the correlation coefficient does not equal 0, so the relationship exists in the population.&lt;/li&gt;
&lt;li&gt;or on the contrary, the sample does not contain enough evidence that the correlation coefficient does not equal 0, so in this case we do not reject the null hypothesis of no relationship between the variables in the population.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that there are 2 assumptions for this test to be valid:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Independence of the data&lt;/li&gt;
&lt;li&gt;For small sample sizes (usually &lt;span class=&#34;math inline&#34;&gt;\(n &amp;lt; 30\)&lt;/span&gt;), the two variables should follow a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Suppose that we want to test whether the rear axle ratio (&lt;code&gt;drat&lt;/code&gt;) is correlated with the time to drive a quarter of a mile (&lt;code&gt;qsec&lt;/code&gt;):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Pearson correlation test
test &amp;lt;- cor.test(dat$drat, dat$qsec)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Pearson&amp;#39;s product-moment correlation
## 
## data:  dat$drat and dat$qsec
## t = 0.50164, df = 30, p-value = 0.6196
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  -0.265947  0.426340
## sample estimates:
##        cor 
## 0.09120476&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value of the correlation test between these 2 variables is 0.62. At the 5% significance level, we do not reject the null hypothesis of no correlation. We therefore conclude that we do not reject the hypothesis that there is no linear relationship between the 2 variables.&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;This test proves that even if the correlation coefficient is different from 0 (the correlation is 0.09 in the sample), it is actually not significantly different from 0 in the population.&lt;/p&gt;
&lt;p&gt;Note that the &lt;em&gt;p&lt;/em&gt;-value of a correlation test is based on the correlation coefficient &lt;strong&gt;and&lt;/strong&gt; the sample size. The larger the sample size and the more extreme the correlation (closer to -1 or 1), the more likely the null hypothesis of no correlation will be rejected.&lt;/p&gt;
&lt;p&gt;With a small sample size, it is thus possible to obtain a &lt;em&gt;relatively&lt;/em&gt; large correlation in the sample (based on the correlation coefficient), but still find a correlation not significantly different from 0 in the population (based on the correlation test). For this reason, it is recommended to always perform a correlation test before interpreting a correlation coefficient to avoid flawed conclusions.&lt;/p&gt;
&lt;!-- A nice and easy way to report results of a correlation test in R is with the `report()` function from the `{report}` package: --&gt;
&lt;!-- As you can see, the function interprets the test (together with the correlation coefficient and the *p*-value) for you. --&gt;
&lt;!-- Note that the `report()` function can be used for other analyses. See more examples in the package&#39;s [documentation](https://easystats.github.io/report/){target=&#34;_blank&#34;}. See also more [tips and tricks in R](/blog/tips-and-tricks-in-rstudio-and-r-markdown/) if you find this one useful. --&gt;
&lt;/div&gt;
&lt;div id=&#34;for-several-pairs-of-variables&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;For several pairs of variables&lt;/h2&gt;
&lt;p&gt;Similar to the correlation matrix used to compute correlation for several pairs of variables, the &lt;code&gt;rcorr()&lt;/code&gt; function (from the &lt;code&gt;{Hmisc}&lt;/code&gt; package) allows to compute &lt;em&gt;p&lt;/em&gt;-values of the correlation test for several pairs of variables at once. Applied to our dataset, we have:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# correlation tests for whole dataset
library(Hmisc)
res &amp;lt;- rcorr(as.matrix(dat)) # rcorr() accepts matrices only

# display p-values (rounded to 3 decimals)
round(res$P, 3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##        mpg   cyl  disp    hp  drat    wt  qsec  gear  carb
## mpg     NA 0.000 0.000 0.000 0.000 0.000 0.017 0.005 0.001
## cyl  0.000    NA 0.000 0.000 0.000 0.000 0.000 0.004 0.002
## disp 0.000 0.000    NA 0.000 0.000 0.000 0.013 0.001 0.025
## hp   0.000 0.000 0.000    NA 0.010 0.000 0.000 0.493 0.000
## drat 0.000 0.000 0.000 0.010    NA 0.000 0.620 0.000 0.621
## wt   0.000 0.000 0.000 0.000 0.000    NA 0.339 0.000 0.015
## qsec 0.017 0.000 0.013 0.000 0.620 0.339    NA 0.243 0.000
## gear 0.005 0.004 0.001 0.493 0.000 0.000 0.243    NA 0.129
## carb 0.001 0.002 0.025 0.000 0.621 0.015 0.000 0.129    NA&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Only correlations with &lt;em&gt;p&lt;/em&gt;-values smaller than the significance level (usually &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;) should be interpreted.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;combination-of-correlation-coefficients-and-correlation-tests&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Combination of correlation coefficients and correlation tests&lt;/h1&gt;
&lt;p&gt;Now that we covered the concepts of correlation coefficients and correlation tests, let see if we can combine the two concepts.&lt;/p&gt;
&lt;p&gt;If you need to do this for a few pairs of variables, I recommend using the &lt;code&gt;ggscatterstats()&lt;/code&gt; function from the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package. Let’s see it in practice with one pair of variables—&lt;code&gt;wt&lt;/code&gt; and &lt;code&gt;mpg&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## plot with statistical results
library(ggstatsplot)

ggscatterstats(
  data = dat,
  x = wt,
  y = mpg,
  bf.message = FALSE,
  marginal = FALSE # remove histograms
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-28-correlation-coefficient-and-correlation-test-in-r_files/figure-html/unnamed-chunk-15-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Based on the result of the test, we conclude that there is a negative correlation between the weight and the number of miles per gallon (&lt;span class=&#34;math inline&#34;&gt;\(r = - 0.87\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &amp;lt; 0.001).&lt;/p&gt;
&lt;p&gt;If you need to do it for many pairs of variables, I recommend using the the &lt;code&gt;correlation&lt;/code&gt; function from the &lt;a href=&#34;https://easystats.github.io/correlation/&#34; target=&#34;_blank&#34;&gt;easystats &lt;code&gt;{correlation}&lt;/code&gt; package&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;This function allows to combine correlation coefficients and correlation tests for &lt;em&gt;several pairs&lt;/em&gt; of variables, all in a single table (thanks to &lt;a href=&#34;https://github.com/AntoineSoetewey/statsandr/issues/8&#34; target=&#34;_blank&#34;&gt;krzysiektr&lt;/a&gt; for pointing it out to me):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(correlation)

correlation::correlation(dat,
  include_factors = TRUE, method = &amp;quot;auto&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # Correlation Matrix (auto-method)
## 
## Parameter1 | Parameter2 |     r |         95% CI | t(30) |         p
## --------------------------------------------------------------------
## mpg        |        cyl | -0.85 | [-0.93, -0.72] | -8.92 | &amp;lt; .001***
## mpg        |       disp | -0.85 | [-0.92, -0.71] | -8.75 | &amp;lt; .001***
## mpg        |         hp | -0.78 | [-0.89, -0.59] | -6.74 | &amp;lt; .001***
## mpg        |       drat |  0.68 | [ 0.44,  0.83] |  5.10 | &amp;lt; .001***
## mpg        |         wt | -0.87 | [-0.93, -0.74] | -9.56 | &amp;lt; .001***
## mpg        |       qsec |  0.42 | [ 0.08,  0.67] |  2.53 | 0.137    
## mpg        |       gear |  0.48 | [ 0.16,  0.71] |  3.00 | 0.065    
## mpg        |       carb | -0.55 | [-0.75, -0.25] | -3.62 | 0.016*   
## cyl        |       disp |  0.90 | [ 0.81,  0.95] | 11.45 | &amp;lt; .001***
## cyl        |         hp |  0.83 | [ 0.68,  0.92] |  8.23 | &amp;lt; .001***
## cyl        |       drat | -0.70 | [-0.84, -0.46] | -5.37 | &amp;lt; .001***
## cyl        |         wt |  0.78 | [ 0.60,  0.89] |  6.88 | &amp;lt; .001***
## cyl        |       qsec | -0.59 | [-0.78, -0.31] | -4.02 | 0.007**  
## cyl        |       gear | -0.49 | [-0.72, -0.17] | -3.10 | 0.054    
## cyl        |       carb |  0.53 | [ 0.22,  0.74] |  3.40 | 0.027*   
## disp       |         hp |  0.79 | [ 0.61,  0.89] |  7.08 | &amp;lt; .001***
## disp       |       drat | -0.71 | [-0.85, -0.48] | -5.53 | &amp;lt; .001***
## disp       |         wt |  0.89 | [ 0.78,  0.94] | 10.58 | &amp;lt; .001***
## disp       |       qsec | -0.43 | [-0.68, -0.10] | -2.64 | 0.131    
## disp       |       gear | -0.56 | [-0.76, -0.26] | -3.66 | 0.015*   
## disp       |       carb |  0.39 | [ 0.05,  0.65] |  2.35 | 0.177    
## hp         |       drat | -0.45 | [-0.69, -0.12] | -2.75 | 0.110    
## hp         |         wt |  0.66 | [ 0.40,  0.82] |  4.80 | &amp;lt; .001***
## hp         |       qsec | -0.71 | [-0.85, -0.48] | -5.49 | &amp;lt; .001***
## hp         |       gear | -0.13 | [-0.45,  0.23] | -0.69 | &amp;gt; .999   
## hp         |       carb |  0.75 | [ 0.54,  0.87] |  6.21 | &amp;lt; .001***
## drat       |         wt | -0.71 | [-0.85, -0.48] | -5.56 | &amp;lt; .001***
## drat       |       qsec |  0.09 | [-0.27,  0.43] |  0.50 | &amp;gt; .999   
## drat       |       gear |  0.70 | [ 0.46,  0.84] |  5.36 | &amp;lt; .001***
## drat       |       carb | -0.09 | [-0.43,  0.27] | -0.50 | &amp;gt; .999   
## wt         |       qsec | -0.17 | [-0.49,  0.19] | -0.97 | &amp;gt; .999   
## wt         |       gear | -0.58 | [-0.77, -0.29] | -3.93 | 0.008**  
## wt         |       carb |  0.43 | [ 0.09,  0.68] |  2.59 | 0.132    
## qsec       |       gear | -0.21 | [-0.52,  0.15] | -1.19 | &amp;gt; .999   
## qsec       |       carb | -0.66 | [-0.82, -0.40] | -4.76 | &amp;lt; .001***
## gear       |       carb |  0.27 | [-0.08,  0.57] |  1.56 | 0.774    
## 
## p-value adjustment method: Holm (1979)
## Observations: 32&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, it gives, among other useful information, the correlation coefficients (column &lt;code&gt;r&lt;/code&gt;) and the result of the correlation test (column &lt;code&gt;95% CI&lt;/code&gt; for the confidence interval or &lt;code&gt;p&lt;/code&gt; for the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value) for all pairs of variables.&lt;/p&gt;
&lt;div id=&#34;correlograms&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Correlograms&lt;/h2&gt;
&lt;p&gt;The table above is very useful and informative, but let see if it is possible to combine the concepts of correlation coefficients and correlations test in one single visualization. A visualization that would be easy to read and interpret.&lt;/p&gt;
&lt;p&gt;Ideally, we would like to have a concise overview of correlations between all possible pairs of variables present in a dataset, with a clear distinction for correlations that are significantly different from 0.&lt;/p&gt;
&lt;p&gt;The figure below, known as a &lt;a href=&#34;https://statsandr.com/blog/correlogram-in-r-how-to-highlight-the-most-correlated-variables-in-a-dataset/#correlogram&#34;&gt;correlogram&lt;/a&gt; and adapted from the &lt;code&gt;corrplot()&lt;/code&gt; function, does precisely this:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# do not edit
corrplot2 &amp;lt;- function(data,
                      method = &amp;quot;pearson&amp;quot;,
                      sig.level = 0.05,
                      order = &amp;quot;original&amp;quot;,
                      diag = FALSE,
                      type = &amp;quot;upper&amp;quot;,
                      tl.srt = 90,
                      number.font = 1,
                      number.cex = 1,
                      mar = c(0, 0, 0, 0)) {
  library(corrplot)
  data_incomplete &amp;lt;- data
  data &amp;lt;- data[complete.cases(data), ]
  mat &amp;lt;- cor(data, method = method)
  cor.mtest &amp;lt;- function(mat, method) {
    mat &amp;lt;- as.matrix(mat)
    n &amp;lt;- ncol(mat)
    p.mat &amp;lt;- matrix(NA, n, n)
    diag(p.mat) &amp;lt;- 0
    for (i in 1:(n - 1)) {
      for (j in (i + 1):n) {
        tmp &amp;lt;- cor.test(mat[, i], mat[, j], method = method)
        p.mat[i, j] &amp;lt;- p.mat[j, i] &amp;lt;- tmp$p.value
      }
    }
    colnames(p.mat) &amp;lt;- rownames(p.mat) &amp;lt;- colnames(mat)
    p.mat
  }
  p.mat &amp;lt;- cor.mtest(data, method = method)
  col &amp;lt;- colorRampPalette(c(&amp;quot;#BB4444&amp;quot;, &amp;quot;#EE9988&amp;quot;, &amp;quot;#FFFFFF&amp;quot;, &amp;quot;#77AADD&amp;quot;, &amp;quot;#4477AA&amp;quot;))
  corrplot(mat,
    method = &amp;quot;color&amp;quot;, col = col(200), number.font = number.font,
    mar = mar, number.cex = number.cex,
    type = type, order = order,
    addCoef.col = &amp;quot;black&amp;quot;, # add correlation coefficient
    tl.col = &amp;quot;black&amp;quot;, tl.srt = tl.srt, # rotation of text labels
    # combine with significance level
    p.mat = p.mat, sig.level = sig.level, insig = &amp;quot;blank&amp;quot;,
    # hide correlation coefficients on the diagonal
    diag = diag
  )
}

# edit from here
corrplot2(
  data = dat,
  method = &amp;quot;pearson&amp;quot;,
  sig.level = 0.05,
  order = &amp;quot;original&amp;quot;,
  diag = FALSE,
  type = &amp;quot;upper&amp;quot;,
  tl.srt = 75
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-28-correlation-coefficient-and-correlation-test-in-r_files/figure-html/unnamed-chunk-17-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The correlogram shows correlation coefficients for all pairs of variables (with more intense colors for more extreme correlations), and correlations not significantly different from 0 are represented by a white box.&lt;/p&gt;
&lt;p&gt;To learn more about this plot and the code used, I invite you to read the article entitled “&lt;a href=&#34;https://statsandr.com/blog/correlogram-in-r-how-to-highlight-the-most-correlated-variables-in-a-dataset/&#34;&gt;Correlogram in R: how to highlight the most correlated variables in a dataset&lt;/a&gt;”.&lt;/p&gt;
&lt;p&gt;For those of you who are still not completely satisfied, I recently found two alternatives—one with the &lt;code&gt;ggpairs()&lt;/code&gt; function from the &lt;code&gt;{GGally}&lt;/code&gt; package and one with the &lt;code&gt;ggcormat()&lt;/code&gt; function from the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package.&lt;/p&gt;
&lt;p&gt;The two functions are illustrated with the variables &lt;code&gt;mpg&lt;/code&gt;, &lt;code&gt;hp&lt;/code&gt; and &lt;code&gt;wt&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(GGally)

ggpairs(dat[, c(&amp;quot;mpg&amp;quot;, &amp;quot;hp&amp;quot;, &amp;quot;wt&amp;quot;)])&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-28-correlation-coefficient-and-correlation-test-in-r_files/figure-html/unnamed-chunk-18-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The plot above combines correlation coefficients, correlation tests (via the asterisks next to the coefficients&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;) and scatterplots for all possible pairs of variables present in a dataset.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggstatsplot)

ggcorrmat(
  data = dat[, c(&amp;quot;mpg&amp;quot;, &amp;quot;hp&amp;quot;, &amp;quot;wt&amp;quot;)],
  type = &amp;quot;parametric&amp;quot;, # parametric for Pearson, nonparametric for Spearman&amp;#39;s correlation
  colors = c(&amp;quot;darkred&amp;quot;, &amp;quot;white&amp;quot;, &amp;quot;steelblue&amp;quot;) # change default colors
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-28-correlation-coefficient-and-correlation-test-in-r_files/figure-html/unnamed-chunk-19-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The plot above also shows the correlation coefficients and if any, the non-significant correlations (by default at the 5% significance level with the Holm adjustment method) are shown by a big cross on the correlation coefficients.&lt;/p&gt;
&lt;p&gt;The advantage of these two alternatives compared to the first one is that it is directly available within a package, so you do not need to run the code of the function first in order to draw the correlogram.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;correlation-does-not-imply-causation&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Correlation does not imply causation&lt;/h1&gt;
&lt;p&gt;I am pretty sure you have already heard the statement “Correlation does not imply causation” in statistics. An article about correlation would not be complete without discussing about causation.&lt;/p&gt;
&lt;p&gt;A non-zero correlation between two variables does not necessarily mean that there is a cause and effect relationship between these two variables!&lt;/p&gt;
&lt;p&gt;Indeed, a significant correlation between two variables means that changes in one variable are associated (positively or negatively) with changes in the other variable. Nonetheless, a significant correlation &lt;em&gt;does not&lt;/em&gt; indicate that variations in one variable &lt;em&gt;cause&lt;/em&gt; the variations in the other variable.&lt;/p&gt;
&lt;p&gt;A non-zero correlation between X and Y can appear in several cases:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;X causes Y&lt;/li&gt;
&lt;li&gt;Y causes X&lt;/li&gt;
&lt;li&gt;a third variable causes X and Y&lt;/li&gt;
&lt;li&gt;a combination of these three reasons&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Sometimes it is quite clear that there is a causal relationship between two variables. Take for example the correlation between the price of a consumer product such as milk and its consumption. It is quite obvious that there is a causal link between the two: if the price of milk increases, it is expected that its consumption will decrease.&lt;/p&gt;
&lt;p&gt;However, this causal link is not always present even if the correlation is significant. &lt;span class=&#34;citation&#34;&gt;Maurage et al. (&lt;a href=&#34;#ref-maurage2013does&#34;&gt;2013&lt;/a&gt;)&lt;/span&gt; showed that, although there is a positive and significant correlation between chocolate consumption and the number of Nobel laureates, this correlation comes from the fact that a third variable, Gross Domestic Product (GDP), causes chocolate consumption and the number of Nobel laureates. They found that countries with higher GDP tend to have a higher level of chocolate consumption and scientific research (leading to more Nobel laureates).&lt;/p&gt;
&lt;p&gt;This example shows that one must be very cautious when interpreting correlations and avoid over-interpreting a correlation as a causal relationship.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to compute correlation coefficients and perform correlation tests in R. If you would like to learn how to compute the coefficients by hand, see this &lt;a href=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/&#34;&gt;step-by-step tutorial&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;(Note that this article is available for download on my &lt;a href=&#34;https://statsandr.gumroad.com/&#34;&gt;Gumroad page&lt;/a&gt;.)&lt;/em&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-maurage2013does&#34; class=&#34;csl-entry&#34;&gt;
Maurage, Pierre, Alexandre Heeren, and Mauro Pesenti. 2013. &lt;span&gt;“Does Chocolate Consumption Really Boost Nobel Award Chances? The Peril of over-Interpreting Correlations in Health Studies.”&lt;/span&gt; &lt;em&gt;The Journal of Nutrition&lt;/em&gt; 143 (6): 931–33.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;It is true that there is the point-biserial correlation which can be used with a nominal variable (consisting of two factors). Nonetheless, this type of correlation is much less known and usually not covered in introductory statistics classes; with one continuous and one nominal variable, it is much more frequent to learn about the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test&lt;/a&gt; (for a nominal variable with 2 groups) or &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;ANOVA&lt;/a&gt; (for a nominal variable with 3 or more groups). More information about choosing the most appropriate measure of association depending on the type of variable can be found in this &lt;a href=&#34;https://journals.sagepub.com/doi/pdf/10.1177/8756479308317006&#34; target=&#34;_blank&#34;&gt;article&lt;/a&gt;.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;It is important to remember that we tested for a &lt;em&gt;linear&lt;/em&gt; relationship between the two variables since we used the Pearson’s correlation. It may be the case that there is a relationship between the two variables in the population, but this relation may not be linear.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;One asterisk means that the coefficient is significant at the 5% level, 2 is at the 1% significance level, and 3 is at the 0.1% significance level. This is usually the case in R; the more asterisks, the more it is significant.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>One-proportion and chi-square goodness of fit test</title>
      <link>https://statsandr.com/blog/one-proportion-and-goodness-of-fit-test-in-r-and-by-hand/</link>
      <pubDate>Wed, 13 May 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/one-proportion-and-goodness-of-fit-test-in-r-and-by-hand/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#in-r&#34; id=&#34;toc-in-r&#34;&gt;In R&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#data&#34; id=&#34;toc-data&#34;&gt;Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#one-proportion-test&#34; id=&#34;toc-one-proportion-test&#34;&gt;One-proportion test&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#assumption-of-prop.test-and-binom.test&#34; id=&#34;toc-assumption-of-prop.test-and-binom.test&#34;&gt;Assumption of &lt;code&gt;prop.test()&lt;/code&gt; and &lt;code&gt;binom.test()&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#chi-square-goodness-of-fit-test&#34; id=&#34;toc-chi-square-goodness-of-fit-test&#34;&gt;Chi-square goodness of fit test&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#assumptions&#34; id=&#34;toc-assumptions&#34;&gt;Assumptions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#does-my-distribution-follow-a-given-distribution&#34; id=&#34;toc-does-my-distribution-follow-a-given-distribution&#34;&gt;Does my distribution follow a given distribution?&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#observed-frequencies&#34; id=&#34;toc-observed-frequencies&#34;&gt;Observed frequencies&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#expected-frequencies&#34; id=&#34;toc-expected-frequencies&#34;&gt;Expected frequencies&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#observed-vs.-expected-frequencies&#34; id=&#34;toc-observed-vs.-expected-frequencies&#34;&gt;Observed vs. expected frequencies&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand&#34; id=&#34;toc-by-hand&#34;&gt;By hand&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#one-proportion-test-1&#34; id=&#34;toc-one-proportion-test-1&#34;&gt;One-proportion test&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#verification-in-r&#34; id=&#34;toc-verification-in-r&#34;&gt;Verification in R&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#goodness-of-fit-test&#34; id=&#34;toc-goodness-of-fit-test&#34;&gt;Goodness of fit test&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#verification-in-r-1&#34; id=&#34;toc-verification-in-r-1&#34;&gt;Verification in R&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-13-one-proportion-and-goodness-of-fit-test-in-r-and-by-hand_files/One-proportion%20and%20goodness%20of%20fit%20test%20in%20R%20and%20by%20hand.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;In a previous article, I presented the &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;Chi-square test of independence in R&lt;/a&gt; which is used to test the independence between two &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;categorical&lt;/a&gt; variables.&lt;/p&gt;
&lt;p&gt;In this article, I show how to perform, first in R and then by hand, the:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;one-proportion test (also referred as one-sample proportion test)&lt;/li&gt;
&lt;li&gt;Chi-square goodness of fit test&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The first test is used to compare an observed proportion to an expected proportion, when the qualitative variable has only &lt;strong&gt;two categories&lt;/strong&gt;. The second test is used to compare multiple observed proportions to multiple expected proportions, in a situation where the qualitative variable has &lt;strong&gt;two or more categories&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Both tests allow to test the equality of proportions between the levels of the qualitative variable or to test the equality with given proportions. These given proportions could be determined arbitrarily or based on the theoretical probabilities of a known distribution.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;In R&lt;/h1&gt;
&lt;div id=&#34;data&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Data&lt;/h2&gt;
&lt;p&gt;For this section, we use the same dataset than in the article on &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt;. It is the well-known &lt;code&gt;iris&lt;/code&gt; dataset, to which we add the variable &lt;code&gt;size&lt;/code&gt;. The variable &lt;code&gt;size&lt;/code&gt; corresponds to &lt;code&gt;small&lt;/code&gt; if the length of the petal is smaller than the median of all flowers, &lt;code&gt;big&lt;/code&gt; otherwise:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load iris dataset
dat &amp;lt;- iris

# create size variable
dat$size &amp;lt;- ifelse(dat$Sepal.Length &amp;lt; median(dat$Sepal.Length),
  &amp;quot;small&amp;quot;, &amp;quot;big&amp;quot;
)

# show first 5 observations
head(dat, n = 5)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species  size
## 1          5.1         3.5          1.4         0.2  setosa small
## 2          4.9         3.0          1.4         0.2  setosa small
## 3          4.7         3.2          1.3         0.2  setosa small
## 4          4.6         3.1          1.5         0.2  setosa small
## 5          5.0         3.6          1.4         0.2  setosa small&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;one-proportion-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;One-proportion test&lt;/h2&gt;
&lt;p&gt;For this example, we have a sample of 150 flowers and we want to test whether the proportion of small flowers is different than the proportion of big flowers (measured by the variable &lt;code&gt;size&lt;/code&gt;). Here are the number of flowers by size, and the corresponding proportions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# barplot
library(ggplot2)
ggplot(dat) +
  aes(x = size) +
  geom_bar(fill = &amp;quot;#0c4c8a&amp;quot;) +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-13-one-proportion-and-goodness-of-fit-test-in-r-and-by-hand_files/figure-html/unnamed-chunk-2-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# counts by size
table(dat$size)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##   big small 
##    77    73&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# proportions by size, rounded to 2 decimals
round(prop.table(table(dat$size)), 2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##   big small 
##  0.51  0.49&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Among the 150 flowers forming our sample, 51% and 49% are big and small, respectively. To test whether the proportions are different among both sizes, we use the &lt;code&gt;prop.test()&lt;/code&gt; function which accepts the following arguments:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;number of successes&lt;/li&gt;
&lt;li&gt;number of observations/trials&lt;/li&gt;
&lt;li&gt;expected probability (the one we want to test against)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The hypotheses in our example are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: proportions of big and small flowers are equal&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: proportions of big and small flowers are different&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Considering (arbitrarily) that &lt;code&gt;big&lt;/code&gt; is the success, we have:&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# one-proportion test
test &amp;lt;- prop.test(
  x = 77, # number of successes
  n = 150, # total number of trials (77 + 73)
  p = 0.5 # we test for equal proportion so prob = 0.5 in each group
)

test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  1-sample proportions test with continuity correction
## 
## data:  77 out of 150, null probability 0.5
## X-squared = 0.06, df = 1, p-value = 0.8065
## alternative hypothesis: true p is not equal to 0.5
## 95 percent confidence interval:
##  0.4307558 0.5952176
## sample estimates:
##         p 
## 0.5133333&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We obtain an output with:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the null probability (&lt;code&gt;0.5&lt;/code&gt;),&lt;/li&gt;
&lt;li&gt;the test statistic (&lt;code&gt;X-squared = 0.06&lt;/code&gt;),&lt;/li&gt;
&lt;li&gt;the degrees of freedom (&lt;code&gt;df = 1&lt;/code&gt;),&lt;/li&gt;
&lt;li&gt;the &lt;em&gt;p&lt;/em&gt;-value (&lt;code&gt;p-value = 0.8065&lt;/code&gt;),&lt;/li&gt;
&lt;li&gt;the alternative hypothesis (&lt;code&gt;true p is not equal to 0.5&lt;/code&gt;),&lt;/li&gt;
&lt;li&gt;the 95% confidence interval (which can also be extracted with &lt;code&gt;test$conf.int&lt;/code&gt;) and&lt;/li&gt;
&lt;li&gt;the proportion in the sample (&lt;code&gt;0.5133333&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.806 so, at the 5% significance level, we do not reject the null hypothesis that the proportions of small and big flowers are the same.&lt;/p&gt;
&lt;p&gt;An alternative is the &lt;code&gt;ggpiestats()&lt;/code&gt; function from the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package:&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## plot with statistical results
library(ggstatsplot)
ggpiestats(
  data = dat,
  x = size,
  bf.message = FALSE
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-13-one-proportion-and-goodness-of-fit-test-in-r-and-by-hand_files/figure-html/unnamed-chunk-4-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Note that the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value (the value after &lt;code&gt;p =&lt;/code&gt; in the subtitle of the plot) is slightly different because Yates’ continuity correction is not applied in &lt;code&gt;ggpiestats()&lt;/code&gt; while it is applied by default in &lt;code&gt;prop.test()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The conclusion remains however the same, that is, we do not reject the null hypothesis that proportions of big and small flowers are equal.&lt;/p&gt;
&lt;div id=&#34;assumption-of-prop.test-and-binom.test&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Assumption of &lt;code&gt;prop.test()&lt;/code&gt; and &lt;code&gt;binom.test()&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Note that &lt;code&gt;prop.test()&lt;/code&gt; uses a normal approximation to the binomial distribution. Therefore, one assumption of this test is that the sample size is large enough (usually, &lt;em&gt;n &amp;gt; 30&lt;/em&gt;). If the sample size is small, it is recommended to use the exact binomial test.&lt;/p&gt;
&lt;p&gt;The exact binomial test can be performed with the &lt;code&gt;binom.test()&lt;/code&gt; function and accepts the same arguments as the &lt;code&gt;prop.test()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;For this example, suppose now that we have a sample of 12 big and 3 small flowers and we want to test whether the proportions are the same among both sizes:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# barplot
barplot(c(12, 3), # observed counts
  names.arg = c(&amp;quot;big&amp;quot;, &amp;quot;small&amp;quot;), # rename labels
  ylab = &amp;quot;Frequency&amp;quot;, # y-axis label
  xlab = &amp;quot;Size&amp;quot; # x-axis label
)
abline(
  h = 15 / 2, # expected counts in each level
  lty = 2 # dashed line
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-13-one-proportion-and-goodness-of-fit-test-in-r-and-by-hand_files/figure-html/unnamed-chunk-5-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# exact binomial test
test &amp;lt;- binom.test(
  x = 12, # counts of successes
  n = 15, # total counts (12 + 3)
  p = 0.5 # expected proportion
)

test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Exact binomial test
## 
## data:  12 and 15
## number of successes = 12, number of trials = 15, p-value = 0.03516
## alternative hypothesis: true probability of success is not equal to 0.5
## 95 percent confidence interval:
##  0.5191089 0.9566880
## sample estimates:
## probability of success 
##                    0.8&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.035 so, at the 5% significance level, we reject the null hypothesis and we conclude that the proportions of small and big flowers are significantly different. This is equivalent than concluding that the proportion of big flowers is significantly different from 0.5 (since there are only two sizes).&lt;/p&gt;
&lt;p&gt;If you want to test that the proportion of big flowers is greater than 50%, add the &lt;code&gt;alternative = &#34;greater&#34;&lt;/code&gt; argument into the &lt;code&gt;binom.test()&lt;/code&gt; function:&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- binom.test(
  x = 12, # counts of successes
  n = 15, # total counts (12 + 3)
  p = 0.5, # expected proportion
  alternative = &amp;quot;greater&amp;quot; # test that prop of big flowers is &amp;gt; 0.5
)

test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Exact binomial test
## 
## data:  12 and 15
## number of successes = 12, number of trials = 15, p-value = 0.01758
## alternative hypothesis: true probability of success is greater than 0.5
## 95 percent confidence interval:
##  0.5602156 1.0000000
## sample estimates:
## probability of success 
##                    0.8&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.018 so, at the 5% significance level, we reject the null hypothesis and we conclude that the proportion of big flowers is significantly larger than 50%.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;chi-square-goodness-of-fit-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Chi-square goodness of fit test&lt;/h2&gt;
&lt;p&gt;Suppose now that the qualitative variable has more than two levels as it is the case for the variable &lt;code&gt;Species&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# barplot
ggplot(dat) +
  aes(x = Species) +
  geom_bar(fill = &amp;quot;#0c4c8a&amp;quot;) +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-13-one-proportion-and-goodness-of-fit-test-in-r-and-by-hand_files/figure-html/unnamed-chunk-7-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# counts by Species
table(dat$Species)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##     setosa versicolor  virginica 
##         50         50         50&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The variable &lt;code&gt;Species&lt;/code&gt; has 3 levels, with 50 observations in each level.&lt;/p&gt;
&lt;p&gt;Suppose for this example that we want to test whether the 3 species are equally common. If they were equally common, they would be equally distributed and the expected proportions would be &lt;span class=&#34;math inline&#34;&gt;\(\frac{1}{3}\)&lt;/span&gt; for each of the species.&lt;/p&gt;
&lt;p&gt;The hypotheses are now:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: proportions of each species are equal&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: there is at least one species with a different proportion&lt;a href=&#34;#fn4&#34; class=&#34;footnote-ref&#34; id=&#34;fnref4&#34;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This test can be done with the &lt;code&gt;chisq.test()&lt;/code&gt; function, accepting the following arguments:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a numeric vector representing the observed proportions&lt;/li&gt;
&lt;li&gt;a vector of probabilities (of the same length of the observed proportions) representing the expected proportions&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Applied to our research question (i.e., are the 3 species equally common?), we have:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# chi-square goodness of fit test
test &amp;lt;- chisq.test(table(dat$Species), # observed proportions
  p = c(1 / 3, 1 / 3, 1 / 3) # expected proportions
)

test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Chi-squared test for given probabilities
## 
## data:  table(dat$Species)
## X-squared = 0, df = 2, p-value = 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 1 so, at the 5% significance level, we do not reject the null hypothesis that the proportions are equal among all species.&lt;/p&gt;
&lt;p&gt;This was quite obvious even before doing the &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical test&lt;/a&gt; given that there are exactly 50 flowers of each species, so it was easy to see that the species are equally common. We however still did the test to show how it works in practice.&lt;/p&gt;
&lt;p&gt;Note that the alternative proposed by the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package can also be used for a Chi-square goodness of fit test:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## plot with statistical results
ggpiestats(
  data = dat,
  x = Species,
  bf.message = FALSE
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-13-one-proportion-and-goodness-of-fit-test-in-r-and-by-hand_files/figure-html/unnamed-chunk-9-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;assumptions&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Assumptions&lt;/h3&gt;
&lt;p&gt;One of the assumptions of the chi-square goodness of fit test is that the sample size is large enough in order for the chi-square approximation to be valid.&lt;/p&gt;
&lt;p&gt;To be more precise, there must be at least 5 &lt;em&gt;expected&lt;/em&gt; frequencies in each group of your categorical variable. This can be verified as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;chisq.test(table(dat$Species))$expected&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##     setosa versicolor  virginica 
##         50         50         50&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The assumption of sufficiently large sample size is met as all expected frequencies are above 5.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;does-my-distribution-follow-a-given-distribution&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Does my distribution follow a given distribution?&lt;/h3&gt;
&lt;p&gt;In the previous section, we chose the proportions ourselves. The goodness of fit test is also particularly useful to compare observed proportions with expected proportions that are based on some known distribution.&lt;/p&gt;
&lt;p&gt;Remember the hypotheses of the test:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: there is no significant difference between the observed and the expected frequencies&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: there is a significant difference between the observed and the expected frequencies&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For this example, suppose that we measured the number of girls in 100 families of 5 children. We want to test whether the (observed) distribution of number girls follows a binomial distribution.&lt;/p&gt;
&lt;div id=&#34;observed-frequencies&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Observed frequencies&lt;/h4&gt;
&lt;p&gt;Here is the distribution of the number of girls per family in our sample of 100 families of 5 children:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-13-one-proportion-and-goodness-of-fit-test-in-r-and-by-hand_files/figure-html/unnamed-chunk-11-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;And the corresponding frequencies and relative frequencies (remember that the relative frequency is the frequency divided by the total sample size):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# counts
dat&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   Girls Frequency Relative_freq
## 1     0         5          0.05
## 2     1        12          0.12
## 3     2        28          0.28
## 4     3        33          0.33
## 5     4        17          0.17
## 6     5         5          0.05&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;expected-frequencies&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Expected frequencies&lt;/h4&gt;
&lt;p&gt;In order to compare the observed frequencies to a binomial distribution and see if both distributions match, we first need to determine the expected frequencies that would be obtained in case of a binomial distribution.&lt;/p&gt;
&lt;p&gt;The expected frequencies assuming a probability of 0.5 of having a girl (for each of the 5 children) are as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# create expected frequencies for a binomial distribution
x &amp;lt;- 0:5
df &amp;lt;- data.frame(
  Girls = factor(x),
  Expected_relative_freq = dbinom(x, size = 5, prob = 0.5)
)
df$Expected_freq &amp;lt;- df$Expected_relative_freq * 100 # *100 since there are 100 families

# create barplot
p &amp;lt;- ggplot(df, aes(x = Girls, y = Expected_freq)) +
  geom_bar(stat = &amp;quot;identity&amp;quot;, fill = &amp;quot;#F8766D&amp;quot;) +
  xlab(&amp;quot;Number of girls per family&amp;quot;) +
  ylab(&amp;quot;Expected frequency&amp;quot;) +
  labs(title = &amp;quot;Binomial distribution Bi(x, n = 5, p = 0.5)&amp;quot;) +
  theme_minimal()
p&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-13-one-proportion-and-goodness-of-fit-test-in-r-and-by-hand_files/figure-html/unnamed-chunk-13-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# expected relative frequencies and (absolute) frequencies
df&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   Girls Expected_relative_freq Expected_freq
## 1     0                0.03125         3.125
## 2     1                0.15625        15.625
## 3     2                0.31250        31.250
## 4     3                0.31250        31.250
## 5     4                0.15625        15.625
## 6     5                0.03125         3.125&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;observed-vs.-expected-frequencies&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Observed vs. expected frequencies&lt;/h4&gt;
&lt;p&gt;We now compare the observed frequencies to the expected frequencies to see whether the two differ significantly. If the two differ significantly, we reject the hypothesis that the number of girls per family of 5 children follows a binomial distribution. On the other hand, if the observed and expected frequencies are similar, we do not reject the hypothesis that the number of girls per family follows a binomial distribution.&lt;/p&gt;
&lt;p&gt;Visually we have:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# create data
data &amp;lt;- data.frame(
  num_girls = factor(rep(c(0:5), times = 2)),
  Freq = c(dat$Freq, df$Expected_freq),
  obs_exp = c(rep(&amp;quot;observed&amp;quot;, 6), rep(&amp;quot;expected&amp;quot;, 6))
)

# create plot
ggplot() +
  geom_bar(
    data = data, aes(
      x = num_girls, y = Freq,
      fill = obs_exp
    ),
    position = &amp;quot;dodge&amp;quot;, # bar next to each other
    stat = &amp;quot;identity&amp;quot;
  ) +
  ylab(&amp;quot;Frequency&amp;quot;) +
  xlab(&amp;quot;Number of girls per family&amp;quot;) +
  theme_minimal() +
  theme(legend.title = element_blank()) # remove legend title&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-13-one-proportion-and-goodness-of-fit-test-in-r-and-by-hand_files/figure-html/unnamed-chunk-14-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;We see that the observed and expected frequencies are quite similar, so we expect that the number of girls in families of 5 children follows a binomial distribution. However, only the goodness of fit test will confirm our belief:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# chi-square goodness of fit test
test &amp;lt;- chisq.test(dat$Freq, # observed frequencies
  p = df$Expected_relative_freq # expected proportions
)

test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Chi-squared test for given probabilities
## 
## data:  dat$Freq
## X-squared = 3.648, df = 5, p-value = 0.6011&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.601 so, at the 5% significance level, we do not reject the null hypothesis that the observed and expected frequencies are equal. This is equivalent than concluding that we cannot reject the hypothesis that the number of girls in families of 5 children follows a binomial distribution (since the expected frequencies were based on a binomial distribution).&lt;/p&gt;
&lt;p&gt;Note that the chi-square goodness of fit test can of course be performed with other types of distribution than the binomial one. For instance, if you want to test whether an observed distribution follows a Poisson distribution, this test can be used to compare the observed frequencies with the expected proportions that would be obtained in case of a Poisson distribution.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;by-hand&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;By hand&lt;/h1&gt;
&lt;p&gt;Now that we showed how to perform the one-proportion and chi-square goodness of fit test in R, in this section we show how to do these tests by hand. We first illustrate the one-proportion test then the chi-square goodness of fit test.&lt;/p&gt;
&lt;div id=&#34;one-proportion-test-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;One-proportion test&lt;/h2&gt;
&lt;p&gt;For this example, suppose that we tossed a coin 100 times and noted that it landed on heads 67 times. Following this, we want to test whether the coin is fair, that is, test whether the probability of landing on heads or tails is equal to 50%.&lt;/p&gt;
&lt;p&gt;As for many &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt;, we do it through 4 easy steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;State the null and alternative hypotheses&lt;/li&gt;
&lt;li&gt;Compute the test-statistic (also known as t-stat)&lt;/li&gt;
&lt;li&gt;Find the rejection region&lt;/li&gt;
&lt;li&gt;Conclude by comparing the test-statistic with the rejection region&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Step 1.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In our example, the null and alternative hypotheses are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(p_0 = 0.5\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(p_0 \ne 0.5\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(p_0\)&lt;/span&gt; is the expected proportion of landing on heads.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 2.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The test statistic is:&lt;a href=&#34;#fn5&#34; class=&#34;footnote-ref&#34; id=&#34;fnref5&#34;&gt;&lt;sup&gt;5&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[z_{obs} = \frac{\hat{p} - p_0}{\sqrt{\frac{p_0(1 - p_0)}{n}}} = \frac{0.67 - 0.5}{\sqrt{\frac{0.5 \cdot (1 - 0.5)}{100}}} = 3.4\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;(See how to perform &lt;a href=&#34;https://statsandr.com/blog/a-shiny-app-for-inferential-statistics-by-hand/&#34;&gt;hypothesis tests in a Shiny app&lt;/a&gt; if you need more help in computing the test statistic.)&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 3.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The rejection region is found via the &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution&lt;/a&gt; table. Assuming a significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;, we have:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-13-one-proportion-and-goodness-of-fit-test-in-r-and-by-hand_files/Screenshot%202020-05-13%20at%2012.23.38.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\pm z_{\alpha/2} = \pm z_{0.025} = \pm 1.96\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 4.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We compare the test statistic (found in step 2) with the rejection region (found in step 3) and we conclude. Visually, we have:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-13-one-proportion-and-goodness-of-fit-test-in-r-and-by-hand_files/figure-html/unnamed-chunk-16-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The test statistic lies within the rejection region (i.e., the grey shaded areas). Therefore, at the 5% significance level, we reject the null hypothesis and we conclude that the proportion of heads (and thus tails) is significantly different than 50%. In other words, still at the 5% significance level, we conclude that the coin is unfair.&lt;/p&gt;
&lt;p&gt;If you prefer to compute the &lt;em&gt;p&lt;/em&gt;-value instead of comparing the t-stat and the rejection region, you can use this &lt;a href=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/&#34;&gt;Shiny app to easily compute &lt;em&gt;p&lt;/em&gt;-values&lt;/a&gt; for different probability distributions. After having opened the app, set the t-stat, the corresponding alternative and you will find the &lt;em&gt;p&lt;/em&gt;-value at the top of the page.&lt;/p&gt;
&lt;div id=&#34;verification-in-r&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Verification in R&lt;/h3&gt;
&lt;p&gt;Just for the sake of illustration, here is the verification of the above example in R:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# one-proportion test
test &amp;lt;- prop.test(
  x = 67, # number of heads
  n = 100, # number of trials
  p = 0.5 # expected probability of heads
)

test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  1-sample proportions test with continuity correction
## 
## data:  67 out of 100, null probability 0.5
## X-squared = 10.89, df = 1, p-value = 0.0009668
## alternative hypothesis: true p is not equal to 0.5
## 95 percent confidence interval:
##  0.5679099 0.7588442
## sample estimates:
##    p 
## 0.67&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.001 so, at the 5% significance level, we reject the null hypothesis that the proportions of heads and tails are equal, and we conclude that the coin is biased. This is the same conclusion than the one found by hand.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;goodness-of-fit-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Goodness of fit test&lt;/h2&gt;
&lt;p&gt;We now illustrate the chi-square goodness of fit test by hand with the following example.&lt;/p&gt;
&lt;p&gt;Suppose that we toss a dice 100 times, we note how many times it lands on each face (1 to 6) and we test whether the dice is fair. Here are the observed counts by dice face:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-13-one-proportion-and-goodness-of-fit-test-in-r-and-by-hand_files/figure-html/unnamed-chunk-18-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## dice_face
##  1  2  3  4  5  6 
## 15 24 10 19 19 13&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With a fair dice, we would expect it to land &lt;span class=&#34;math inline&#34;&gt;\(\frac{100}{6} \approx 16.67\)&lt;/span&gt; times on each face (this expected value is represented by the dashed line in the above plot). Although the observed frequencies are different than the expected value of 16.67:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;##   dice_face observed_freq expected_freq
## 1         1            15         16.67
## 2         2            24         16.67
## 3         3            10         16.67
## 4         4            19         16.67
## 5         5            19         16.67
## 6         6            13         16.67&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;we need to test whether they are &lt;em&gt;significantly&lt;/em&gt; different. For this, we perform the appropriate &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis test&lt;/a&gt; following the 4 easy steps mentioned above:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;State the null and alternative hypotheses&lt;/li&gt;
&lt;li&gt;Compute the test-statistic (also known as t-stat)&lt;/li&gt;
&lt;li&gt;Find the rejection region&lt;/li&gt;
&lt;li&gt;Conclude by comparing the test-statistic with the rejection region&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Step 1.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The null and alternative hypotheses of the chi-square goodness of fit test are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: there is no significant difference between the observed and the expected frequencies&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: there is a significant difference between the observed and the expected frequencies&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Applied to our example, we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: all faces occur in the same proportion&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: at least one proportion is not equal to 1/6&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Step 2.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The test statistic is:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\chi^2 = \sum_{i = 1}^k \frac{(O_i - E_i)^2}{E_i}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(O_i\)&lt;/span&gt; is the observed frequency, &lt;span class=&#34;math inline&#34;&gt;\(E_i\)&lt;/span&gt; is the expected frequency and &lt;span class=&#34;math inline&#34;&gt;\(k\)&lt;/span&gt; is the number of categories (in our case, there are 6 categories, representing the 6 dice faces).&lt;/p&gt;
&lt;p&gt;This &lt;span class=&#34;math inline&#34;&gt;\(\chi^2\)&lt;/span&gt; statistic is obtained by calculating the difference between the observed number of cases and the expected number of cases in each category. This difference is squared (to avoid negative and positive differences being compensated) and divided by the expected number of cases in that category. These values are then summed for all categories, and the total is referred to as the &lt;span class=&#34;math inline&#34;&gt;\(\chi^2\)&lt;/span&gt; statistic. Large values of this test statistic lead to the rejection of the null hypothesis, small values mean that the null hypothesis cannot be rejected.&lt;a href=&#34;#fn6&#34; class=&#34;footnote-ref&#34; id=&#34;fnref6&#34;&gt;&lt;sup&gt;6&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Given our data, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\chi^2 = \frac{(15 - 16.67)^2}{16.67} + \frac{(24 - 16.67)^2}{16.67} + \\
\frac{(10 - 16.67)^2}{16.67} +\frac{(19 - 16.67)^2}{16.67} + \\
\frac{(19 - 16.67)^2}{16.67} + \frac{(13 - 16.67)^2}{16.67}  =  7.52\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 3.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Whether the &lt;span class=&#34;math inline&#34;&gt;\(\chi^2\)&lt;/span&gt; test statistic is small or large depends on the rejection region. The rejection region is found via the &lt;span class=&#34;math inline&#34;&gt;\(\chi^2\)&lt;/span&gt; distribution table. With a degrees of freedom equals to &lt;span class=&#34;math inline&#34;&gt;\(k - 1\)&lt;/span&gt; (where &lt;span class=&#34;math inline&#34;&gt;\(k\)&lt;/span&gt; is the number of categories) and assuming a significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;, we have:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-13-one-proportion-and-goodness-of-fit-test-in-r-and-by-hand_files/Screenshot%202020-05-13%20at%2012.20.42.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\chi^2_{\alpha; k-1} = \chi^2_{0.05; 5} = 11.0705\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 4.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We compare the test statistic (found in step 2) with the rejection region (found in step 3) and we conclude. Visually, we have:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-05-13-one-proportion-and-goodness-of-fit-test-in-r-and-by-hand_files/figure-html/unnamed-chunk-20-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The test statistic does not lie within the rejection region (i.e., the grey shaded area). Therefore, at the 5% significance level, we do not reject the null hypothesis that there is no significant difference between the observed and the expected frequencies. In other words, still at the 5% significance level, we cannot reject the hypothesis that the dice is fair.&lt;/p&gt;
&lt;p&gt;Again, you can use the &lt;a href=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/&#34;&gt;Shiny app&lt;/a&gt; to easily compute the &lt;em&gt;p&lt;/em&gt;-value given the test statistic if you prefer this method over the comparison between the t-stat and the rejection region.&lt;/p&gt;
&lt;div id=&#34;verification-in-r-1&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Verification in R&lt;/h3&gt;
&lt;p&gt;Just for the sake of illustration, here is the verification of the above example in R:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# chi-square goodness of fit test
test &amp;lt;- chisq.test(dat$observed_freq, # observed frequencies for each dice face
  p = rep(1 / 6, 6) # expected probabilities for each dice face
)

test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Chi-squared test for given probabilities
## 
## data:  dat$observed_freq
## X-squared = 7.52, df = 5, p-value = 0.1847&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The test statistic and degrees of freedom are exactly the same than the ones found by hand. The &lt;em&gt;p&lt;/em&gt;-value is 0.185 which, still at the 5% significance level, leads to the same conclusion than by hand (i.e., failing to reject the null hypothesis).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to understand and perform the one-proportion and chi-square goodness of fit test in R and by hand. Learn more about the Chi-square test of independence &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;in R&lt;/a&gt; and &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-by-hand/&#34;&gt;by hand&lt;/a&gt; if you want to analyze &lt;em&gt;two&lt;/em&gt; categorical variables instead of one.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;Choosing big or small as the success event gives the exact same conclusion.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Note that if possible, it is best to avoid pie charts and use bar charts instead. Unfortunately, the &lt;code&gt;ggbarstats()&lt;/code&gt; function works only for the &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;independence Chi-square test&lt;/a&gt;.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;Similarly, this argument can also be added to the &lt;code&gt;prop.test()&lt;/code&gt; function to test whether the observed proportion is larger than the expected proportion. Use &lt;code&gt;alternative = &#34;less&#34;&lt;/code&gt; if you want to test whether the observed proportion is smaller than the expected one.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;Be careful that the alternative hypothesis is not that &lt;em&gt;all&lt;/em&gt; proportions are different. One different from the others is sufficient to reject the null hypothesis. It is, in some sense, similar to the alternative hypothesis of the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;ANOVA&lt;/a&gt; which says that at least one mean is different than another.&lt;a href=&#34;#fnref4&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn5&#34;&gt;&lt;p&gt;One assumption of this test is that &lt;span class=&#34;math inline&#34;&gt;\(n \cdot p \ge 5\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(n \cdot (1 - p) \ge 5\)&lt;/span&gt;. The assumption is met so we can use the normal approximation to the binomial distribution.&lt;a href=&#34;#fnref5&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn6&#34;&gt;&lt;p&gt;Source: &lt;a href=&#34;http://uregina.ca/~gingrich/ch10.pdf&#34; target=&#34;_blank&#34;&gt;http://uregina.ca/~gingrich/ch10.pdf&lt;/a&gt;.&lt;a href=&#34;#fnref6&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>How to do a t-test or ANOVA for more than one variable at once in R?</title>
      <link>https://statsandr.com/blog/how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way/</link>
      <pubDate>Thu, 19 Mar 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#perform-multiple-tests-at-once&#34; id=&#34;toc-perform-multiple-tests-at-once&#34;&gt;Perform multiple tests at once&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#concise-and-easily-interpretable-results&#34; id=&#34;toc-concise-and-easily-interpretable-results&#34;&gt;Concise and easily interpretable results&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#t-test&#34; id=&#34;toc-t-test&#34;&gt;T-test&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#additional-p-value-adjustment-methods&#34; id=&#34;toc-additional-p-value-adjustment-methods&#34;&gt;Additional &lt;em&gt;p&lt;/em&gt;-value adjustment methods&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#anova&#34; id=&#34;toc-anova&#34;&gt;ANOVA&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#to-go-even-further&#34; id=&#34;toc-to-go-even-further&#34;&gt;To go even further&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#update-with-the-ggstatsplot-package&#34; id=&#34;toc-update-with-the-ggstatsplot-package&#34;&gt;Update with the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/How%20to%20do%20a%20t-test%20or%20ANOVA%20for%20many%20variables%20at%20once%20in%20R%20and%20communicate%20the%20results%20in%20a%20better%20way.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;As part of my teaching assistant position in a Belgian university, students often ask me for some help in their statistical analyses for their master’s thesis.&lt;/p&gt;
&lt;p&gt;A frequent question is how to compare groups of patients in terms of several &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#continuous&#34;&gt;quantitative continuous&lt;/a&gt; variables. Most of us know that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;To compare two groups, a &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test&lt;/a&gt; should be used&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;To compare three groups or more, an &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;ANOVA&lt;/a&gt; should be performed&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These two tests are quite basic and have been extensively documented online and in statistical textbooks so the difficulty is not in how to perform these tests.&lt;/p&gt;
&lt;p&gt;In the past, I used to do the analyses by following these 3 steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Draw boxplots illustrating the distributions by group (with the &lt;code&gt;boxplot()&lt;/code&gt; function or thanks to the &lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#esquisse&#34;&gt;&lt;code&gt;{esquisse}&lt;/code&gt; R Studio addin&lt;/a&gt; if I wanted to use the &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;&lt;code&gt;{ggplot2}&lt;/code&gt; package&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;Perform a t-test or an ANOVA depending on the number of groups to compare (with the &lt;code&gt;t.test()&lt;/code&gt; and &lt;code&gt;oneway.test()&lt;/code&gt; functions for t-test and ANOVA, respectively)&lt;/li&gt;
&lt;li&gt;Repeat steps 1 and 2 for each variable&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This was feasible as long as there were only a couple of variables to test. Nonetheless, most students came to me asking to perform these kind of tests not on one or two variables, but on &lt;strong&gt;multiples&lt;/strong&gt; variables. So when there were more than one variable to test, I quickly realized that I was wasting my time and that there must be a more efficient way to do the job.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note&lt;/strong&gt;: you must be very careful with the issue of &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#issue-of-multiple-testing&#34;&gt;multiple testing&lt;/a&gt; (also referred as multiplicity) which can arise when you perform multiple tests. In short, when a large number of statistical tests are performed, some will have &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values less than 0.05 purely by chance, even if all null hypotheses are in fact really true. This is known as multiplicity or multiple testing. You can tackle this problem by using the Bonferroni correction, among others. The Bonferroni correction is a simple method that allows many t-tests to be made while still assuring an overall confidence level is maintained. For this, instead of using the standard threshold of &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 5\)&lt;/span&gt;% for the significance level, you can use &lt;span class=&#34;math inline&#34;&gt;\(\alpha = \frac{0.05}{m}\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(m\)&lt;/span&gt; is the number of t-tests. For example, if you perform 20 t-tests with a desired &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;, the Bonferroni correction implies that you would reject the null hypothesis for each individual test when the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value is smaller than &lt;span class=&#34;math inline&#34;&gt;\(\alpha = \frac{0.05}{20} = 0.0025\)&lt;/span&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Note also that there is no universally accepted approach for dealing with the problem of multiple comparisons. Usually, you should choose a &lt;em&gt;p&lt;/em&gt;-value adjustment measure familiar to your audience or in your field of study. The Bonferroni correction is easy to implement. It is however not appropriate if you have a very large number of tests to perform (imagine you want to do 10,000 t-tests, a &lt;em&gt;p&lt;/em&gt;-value would have to be less than &lt;span class=&#34;math inline&#34;&gt;\(\frac{0.05}{10000} = 0.000005\)&lt;/span&gt; to be significant). A more powerful method is also to adjust the false discovery rate using the Benjamini-Hochberg or Holm procedure &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-mcdonald2014multiple&#34;&gt;McDonald 2014&lt;/a&gt;)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Another option is to use a multivariate ANOVA (MANOVA), if your independent variable has more than two levels. This is particularly useful when your dependent variables are correlated. Correlation between the dependent variables provides MANOVA the following advantages:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Identify patterns between several dependent variables&lt;/strong&gt;: The independent variables can influence the relationship between dependent variables instead of influencing a single dependent variable.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Address the issue of multiple testing&lt;/strong&gt;: with MANOVA, the error rate equals the significance level (with no &lt;em&gt;p&lt;/em&gt;-value adjustment method needed).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Greater statistical power&lt;/strong&gt;: When the dependent variables are correlated, MANOVA can identify effects that are too small for the ANOVA to detect.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that MANOVA is used if your independent variable has more than two levels. If your independent variable has only two levels, the multivariate equivalent of the t-test is Hotelling’s &lt;span class=&#34;math inline&#34;&gt;\(T^2\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;This article aims at presenting a way to perform multiple t-tests and ANOVA from a &lt;strong&gt;technical point of view&lt;/strong&gt; (how to implement it in R). Discussion on which adjustment method to use or whether there is a more appropriate model to fit the data is beyond the scope of this article (so be sure to understand the implications of using the code below for your own analyses). Make sure also to test the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#underlying-assumptions-of-anova&#34;&gt;assumptions&lt;/a&gt; of the ANOVA before interpreting results.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;perform-multiple-tests-at-once&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Perform multiple tests at once&lt;/h1&gt;
&lt;p&gt;I thus wrote a piece of code that automated the process, by drawing boxplots and performing the tests on several variables at once. Below is the code I used, illustrating the process with the &lt;code&gt;iris&lt;/code&gt; dataset. The &lt;code&gt;Species&lt;/code&gt; variable has 3 levels, so let’s remove one, and then draw a boxplot and apply a t-test on all 4 continuous variables at once. Note that the continuous variables that we would like to test are variables 1 to 4 in the &lt;code&gt;iris&lt;/code&gt; dataset.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- iris

# remove one level to have only two groups
dat &amp;lt;- subset(dat, Species != &amp;quot;setosa&amp;quot;)
dat$Species &amp;lt;- factor(dat$Species)

# boxplots and t-tests for the 4 variables at once
for (i in 1:4) { # variables to compare are variables 1 to 4
  boxplot(dat[, i] ~ dat$Species, # draw boxplots by group
    ylab = names(dat[i]), # rename y-axis with variable&amp;#39;s name
    xlab = &amp;quot;Species&amp;quot;
  )
  print(t.test(dat[, i] ~ dat$Species)) # print results of t-test
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-1-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Welch Two Sample t-test
## 
## data:  dat[, i] by dat$Species
## t = -5.6292, df = 94.025, p-value = 1.866e-07
## alternative hypothesis: true difference in means between group versicolor and group virginica is not equal to 0
## 95 percent confidence interval:
##  -0.8819731 -0.4220269
## sample estimates:
## mean in group versicolor  mean in group virginica 
##                    5.936                    6.588&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-1-2.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Welch Two Sample t-test
## 
## data:  dat[, i] by dat$Species
## t = -3.2058, df = 97.927, p-value = 0.001819
## alternative hypothesis: true difference in means between group versicolor and group virginica is not equal to 0
## 95 percent confidence interval:
##  -0.33028364 -0.07771636
## sample estimates:
## mean in group versicolor  mean in group virginica 
##                    2.770                    2.974&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-1-3.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Welch Two Sample t-test
## 
## data:  dat[, i] by dat$Species
## t = -12.604, df = 95.57, p-value &amp;lt; 2.2e-16
## alternative hypothesis: true difference in means between group versicolor and group virginica is not equal to 0
## 95 percent confidence interval:
##  -1.49549 -1.08851
## sample estimates:
## mean in group versicolor  mean in group virginica 
##                    4.260                    5.552&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-1-4.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Welch Two Sample t-test
## 
## data:  dat[, i] by dat$Species
## t = -14.625, df = 89.043, p-value &amp;lt; 2.2e-16
## alternative hypothesis: true difference in means between group versicolor and group virginica is not equal to 0
## 95 percent confidence interval:
##  -0.7951002 -0.6048998
## sample estimates:
## mean in group versicolor  mean in group virginica 
##                    1.326                    2.026&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, the above piece of code draws a boxplot and then prints results of the test for each continuous variable, all at once.&lt;/p&gt;
&lt;p&gt;At some point in the past, I even wrote code to:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;draw a boxplot&lt;/li&gt;
&lt;li&gt;test for the equality of variances (thanks to the Levene’s test)&lt;/li&gt;
&lt;li&gt;depending on whether the variances were equal or unequal, the appropriate test was applied: the Welch test if the variances were unequal and the Student’s t-test in the case the variances were equal (see more details about the different versions of the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;t-test for two samples&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;apply steps 1 to 3 for all continuous variables at once&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;I had a similar code for ANOVA in case I needed to compare more than two groups.&lt;/p&gt;
&lt;p&gt;The code was doing the job relatively well. Indeed, thanks to this code I was able to test several variables in an automated way in the sense that it compared groups for all variables at once.&lt;/p&gt;
&lt;p&gt;The only thing I had to change from one project to another is that I needed to modify the name of the grouping variable and the numbering of the continuous variables to test (&lt;code&gt;Species&lt;/code&gt; and &lt;code&gt;1:4&lt;/code&gt; in the above code).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;concise-and-easily-interpretable-results&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Concise and easily interpretable results&lt;/h1&gt;
&lt;div id=&#34;t-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;T-test&lt;/h2&gt;
&lt;p&gt;Although it was working quite well and applicable to different projects with only minor changes, I was still unsatisfied with another point.&lt;/p&gt;
&lt;p&gt;Someone who is proficient in statistics and R can read and interpret the output of a t-test without any difficulty. However, as you may have noticed with your own statistical projects, most people do not know what to look for in the results and are sometimes a bit confused when they see so many graphs, code, output, results and numeric values in a document. They are quite easily overwhelmed by this mass of information and unable to extract the key message.&lt;/p&gt;
&lt;p&gt;With my old R routine, the time I was saving by automating the process of t-tests and ANOVA was (partially) lost when I had to explain R outputs to my students so that they could interpret the results correctly. Although most of the time it simply boiled down to pointing out what to look for in the outputs (i.e., &lt;em&gt;p&lt;/em&gt;-values), I was still losing quite a lot of time because these outputs were, in my opinion, too detailed for most real-life applications and for students in introductory classes. In other words, too much information seemed to be confusing for many people so I was still not convinced that it was the most optimal way to share statistical results to nonscientists.&lt;/p&gt;
&lt;p&gt;Of course, they came to me for statistical advices, so they expected to have these results and I needed to give them answers to their questions and hypotheses. Nonetheless, I wanted to find a better way to communicate these results to this type of audience, with the minimum of information required to arrive at a conclusion. No more and no less than that.&lt;/p&gt;
&lt;p&gt;After a long time spent online trying to figure out a way to present results in a more concise and readable way, I discovered the &lt;a href=&#34;https://cran.r-project.org/web/packages/ggpubr/index.html&#34; target=&#34;_blank&#34;&gt;&lt;code&gt;{ggpubr}&lt;/code&gt; package&lt;/a&gt;. This package allows to indicate the test used and the &lt;em&gt;p&lt;/em&gt;-value of the test directly on a ggplot2-based graph. It also facilitates the creation of publication-ready plots for non-advanced statistical audiences.&lt;/p&gt;
&lt;p&gt;After many refinements and modifications of the initial code (available in this &lt;a href=&#34;http://www.sthda.com/english/articles/24-ggpubr-publication-ready-plots/76-add-p-values-and-significance-levels-to-ggplots/&#34; target=&#34;_blank&#34;&gt;article&lt;/a&gt;), I finally came up with a rather stable and robust process to perform t-tests and ANOVA for more than one variable at once, and more importantly, make the results concise and easily readable by anyone (statisticians or not).&lt;/p&gt;
&lt;p&gt;A graph is worth a thousand words, so here are the exact same tests than in the previous section, but this time with my new R routine:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggpubr)

# Edit from here #
x &amp;lt;- which(names(dat) == &amp;quot;Species&amp;quot;) # name of grouping variable
y &amp;lt;- which(names(dat) == &amp;quot;Sepal.Length&amp;quot; # names of variables to test
| names(dat) == &amp;quot;Sepal.Width&amp;quot; |
  names(dat) == &amp;quot;Petal.Length&amp;quot; |
  names(dat) == &amp;quot;Petal.Width&amp;quot;)
method &amp;lt;- &amp;quot;t.test&amp;quot; # one of &amp;quot;wilcox.test&amp;quot; or &amp;quot;t.test&amp;quot;
paired &amp;lt;- FALSE # if paired make sure that in the dataframe you have first all individuals at T1, then all individuals again at T2
# Edit until here


# Edit at your own risk
for (i in y) {
  for (j in x) {
    if (paired == TRUE) {
      p &amp;lt;- ggpaired(dat,
        x = colnames(dat[j]), y = colnames(dat[i]),
        color = colnames(dat[j]), line.color = &amp;quot;gray&amp;quot;, line.size = 0.4,
        palette = &amp;quot;npg&amp;quot;,
        legend = &amp;quot;none&amp;quot;,
        xlab = colnames(dat[j]),
        ylab = colnames(dat[i]),
        add = &amp;quot;jitter&amp;quot;
      )
    } else {
      p &amp;lt;- ggboxplot(dat,
        x = colnames(dat[j]), y = colnames(dat[i]),
        color = colnames(dat[j]),
        palette = &amp;quot;npg&amp;quot;,
        legend = &amp;quot;none&amp;quot;,
        add = &amp;quot;jitter&amp;quot;
      )
    }
    #  Add p-value
    print(p + stat_compare_means(aes(label = paste0(after_stat(method), &amp;quot;, p-value = &amp;quot;, after_stat(p.format))),
      method = method,
      paired = paired,
      # group.by = NULL,
      ref.group = NULL
    ))
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-2-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-2-2.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-2-3.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-2-4.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;As you can see from the graphs above, only the most important information is presented for each variable:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a visual comparison of the groups thanks to boxplots&lt;/li&gt;
&lt;li&gt;the name of the &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical test&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;the &lt;em&gt;p&lt;/em&gt;-value of the test&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Of course, experts may be interested in more advanced results. However, this simple yet complete graph, which includes the name of the test and the &lt;em&gt;p&lt;/em&gt;-value, gives all the necessary information to answer the question: “Are the groups different?”.&lt;/p&gt;
&lt;p&gt;In my experience, I have noticed that students and professionals (especially those from a less scientific background) understand way better these results than the ones presented in the previous section.&lt;/p&gt;
&lt;p&gt;The only lines of code that need to be modified for your own project is the name of the grouping variable (&lt;code&gt;Species&lt;/code&gt; in the above code), the names of the variables you want to test (&lt;code&gt;Sepal.Length&lt;/code&gt;, &lt;code&gt;Sepal.Width&lt;/code&gt;, etc.),&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt; whether you want to apply a &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;t-test&lt;/a&gt; (&lt;code&gt;t.test&lt;/code&gt;) or &lt;a href=&#34;https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/&#34;&gt;Wilcoxon test&lt;/a&gt; (&lt;code&gt;wilcox.test&lt;/code&gt;) and whether the samples are paired or not (&lt;code&gt;FALSE&lt;/code&gt; if samples are independent, &lt;code&gt;TRUE&lt;/code&gt; if they are paired).&lt;/p&gt;
&lt;p&gt;Based on these graphs, it is easy, even for non-experts, to interpret the results and conclude that the &lt;code&gt;versicolor&lt;/code&gt; and &lt;code&gt;virginica&lt;/code&gt; species are significantly different in terms of all 4 variables (since all &lt;em&gt;p&lt;/em&gt;-values &lt;span class=&#34;math inline&#34;&gt;\(&amp;lt; \frac{0.05}{4} = 0.0125\)&lt;/span&gt; (remind that the Bonferroni correction is applied to avoid the issue of multiple testing, so we divide the usual &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; level by 4 because there are 4 t-tests)).&lt;/p&gt;
&lt;div id=&#34;additional-p-value-adjustment-methods&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Additional &lt;em&gt;p&lt;/em&gt;-value adjustment methods&lt;/h3&gt;
&lt;p&gt;If you would like to use another &lt;em&gt;p&lt;/em&gt;-value adjustment method, you can use the &lt;code&gt;p.adjust()&lt;/code&gt; function. Below are the raw &lt;em&gt;p&lt;/em&gt;-values found above, together with &lt;em&gt;p&lt;/em&gt;-values derived from the main adjustment methods (presented in a dataframe):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;raw_pvalue &amp;lt;- numeric(length = length(1:4))
for (i in (1:4)) {
  raw_pvalue[i] &amp;lt;- t.test(dat[, i] ~ dat$Species,
    alternative = &amp;quot;two.sided&amp;quot;
  )$p.value
}

df &amp;lt;- data.frame(
  Variable = names(dat[, 1:4]),
  raw_pvalue = round(raw_pvalue, 3)
)

df$Bonferroni &amp;lt;-
  p.adjust(df$raw_pvalue,
    method = &amp;quot;bonferroni&amp;quot;
  )
df$BH &amp;lt;-
  p.adjust(df$raw_pvalue,
    method = &amp;quot;BH&amp;quot;
  )
df$Holm &amp;lt;-
  p.adjust(df$raw_pvalue,
    method = &amp;quot;holm&amp;quot;
  )
df$Hochberg &amp;lt;-
  p.adjust(df$raw_pvalue,
    method = &amp;quot;hochberg&amp;quot;
  )
df$Hommel &amp;lt;-
  p.adjust(df$raw_pvalue,
    method = &amp;quot;hommel&amp;quot;
  )
df$BY &amp;lt;-
  round(p.adjust(df$raw_pvalue,
    method = &amp;quot;BY&amp;quot;
  ), 3)
df&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       Variable raw_pvalue Bonferroni    BH  Holm Hochberg Hommel    BY
## 1 Sepal.Length      0.000      0.000 0.000 0.000    0.000  0.000 0.000
## 2  Sepal.Width      0.002      0.008 0.002 0.002    0.002  0.002 0.004
## 3 Petal.Length      0.000      0.000 0.000 0.000    0.000  0.000 0.000
## 4  Petal.Width      0.000      0.000 0.000 0.000    0.000  0.000 0.000&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Regardless of the &lt;em&gt;p&lt;/em&gt;-value adjustment method, the two species are different for all 4 variables. Note that the adjustment method should be chosen before looking at the results to avoid choosing the method based on the results.&lt;/p&gt;
&lt;p&gt;Below another function that allows to perform multiple Student’s t-tests or Wilcoxon tests at once and choose the &lt;em&gt;p&lt;/em&gt;-value adjustment method. The function also allows to specify whether samples are paired or unpaired and whether the variances are assumed to be equal or not. (The code has been adapted from Mark White’s &lt;a href=&#34;https://www.markhw.com/blog/t-table&#34; target=&#34;_blank&#34;&gt;article&lt;/a&gt;.)&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;t_table &amp;lt;- function(data, dvs, iv,
                    var_equal = TRUE,
                    p_adj = &amp;quot;none&amp;quot;,
                    alpha = 0.05,
                    paired = FALSE,
                    wilcoxon = FALSE) {
  if (!inherits(data, &amp;quot;data.frame&amp;quot;)) {
    stop(&amp;quot;data must be a data.frame&amp;quot;)
  }

  if (!all(c(dvs, iv) %in% names(data))) {
    stop(&amp;quot;at least one column given in dvs and iv are not in the data&amp;quot;)
  }

  if (!all(sapply(data[, dvs], is.numeric))) {
    stop(&amp;quot;all dvs must be numeric&amp;quot;)
  }

  if (length(unique(na.omit(data[[iv]]))) != 2) {
    stop(&amp;quot;independent variable must only have two unique values&amp;quot;)
  }

  out &amp;lt;- lapply(dvs, function(x) {
    if (paired == FALSE &amp;amp; wilcoxon == FALSE) {
      tres &amp;lt;- t.test(data[[x]] ~ data[[iv]], var.equal = var_equal)
    } else if (paired == FALSE &amp;amp; wilcoxon == TRUE) {
      tres &amp;lt;- wilcox.test(data[[x]] ~ data[[iv]])
    } else if (paired == TRUE &amp;amp; wilcoxon == FALSE) {
      tres &amp;lt;- t.test(data[[x]] ~ data[[iv]],
        var.equal = var_equal,
        paired = TRUE
      )
    } else {
      tres &amp;lt;- wilcox.test(data[[x]] ~ data[[iv]],
        paired = TRUE
      )
    }

    c(
      p_value = tres$p.value
    )
  })

  out &amp;lt;- as.data.frame(do.call(rbind, out))
  out &amp;lt;- cbind(variable = dvs, out)
  names(out) &amp;lt;- gsub(&amp;quot;[^0-9A-Za-z_]&amp;quot;, &amp;quot;&amp;quot;, names(out))

  out$p_value &amp;lt;- p.adjust(out$p_value, p_adj)
  out$conclusion &amp;lt;- ifelse(out$p_value &amp;lt; alpha,
    paste0(&amp;quot;Reject H0 at &amp;quot;, alpha * 100, &amp;quot;%&amp;quot;),
    paste0(&amp;quot;Do not reject H0 at &amp;quot;, alpha * 100, &amp;quot;%&amp;quot;)
  )
  out$p_value &amp;lt;- ifelse(out$p_value &amp;lt; 0.001,
    &amp;quot;&amp;lt;0.001&amp;quot;,
    round(out$p_value, 3)
  )

  return(out)
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Applied to our dataset, with no adjustment method for the &lt;em&gt;p&lt;/em&gt;-values:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;result &amp;lt;- t_table(
  data = dat,
  c(&amp;quot;Sepal.Length&amp;quot;, &amp;quot;Sepal.Width&amp;quot;, &amp;quot;Petal.Length&amp;quot;, &amp;quot;Petal.Width&amp;quot;),
  &amp;quot;Species&amp;quot;
)

result&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       variable p_value      conclusion
## 1 Sepal.Length  &amp;lt;0.001 Reject H0 at 5%
## 2  Sepal.Width   0.002 Reject H0 at 5%
## 3 Petal.Length  &amp;lt;0.001 Reject H0 at 5%
## 4  Petal.Width  &amp;lt;0.001 Reject H0 at 5%&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And with the &lt;span class=&#34;citation&#34;&gt;Holm (&lt;a href=&#34;#ref-holm1979simple&#34;&gt;1979&lt;/a&gt;)&lt;/span&gt; adjustment method:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;result &amp;lt;- t_table(
  data = dat,
  c(&amp;quot;Sepal.Length&amp;quot;, &amp;quot;Sepal.Width&amp;quot;, &amp;quot;Petal.Length&amp;quot;, &amp;quot;Petal.Width&amp;quot;),
  &amp;quot;Species&amp;quot;,
  p_adj = &amp;quot;holm&amp;quot;
)

result&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       variable p_value      conclusion
## 1 Sepal.Length  &amp;lt;0.001 Reject H0 at 5%
## 2  Sepal.Width   0.002 Reject H0 at 5%
## 3 Petal.Length  &amp;lt;0.001 Reject H0 at 5%
## 4  Petal.Width  &amp;lt;0.001 Reject H0 at 5%&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Again, with the Holm’s adjustment method, we conclude that, at the 5% significance level, the two species are significantly different from each other in terms of all 4 variables.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;anova&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;ANOVA&lt;/h2&gt;
&lt;p&gt;Below the same process with an ANOVA. Note that we reload the dataset &lt;code&gt;iris&lt;/code&gt; to include all three &lt;code&gt;Species&lt;/code&gt; this time:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- iris

# Edit from here
x &amp;lt;- which(names(dat) == &amp;quot;Species&amp;quot;) # name of grouping variable
y &amp;lt;- which(names(dat) == &amp;quot;Sepal.Length&amp;quot; # names of variables to test
| names(dat) == &amp;quot;Sepal.Width&amp;quot; |
  names(dat) == &amp;quot;Petal.Length&amp;quot; |
  names(dat) == &amp;quot;Petal.Width&amp;quot;)
method1 &amp;lt;- &amp;quot;anova&amp;quot; # one of &amp;quot;anova&amp;quot; or &amp;quot;kruskal.test&amp;quot;
method2 &amp;lt;- &amp;quot;t.test&amp;quot; # one of &amp;quot;wilcox.test&amp;quot; or &amp;quot;t.test&amp;quot;
my_comparisons &amp;lt;- list(c(&amp;quot;setosa&amp;quot;, &amp;quot;versicolor&amp;quot;), c(&amp;quot;setosa&amp;quot;, &amp;quot;virginica&amp;quot;), c(&amp;quot;versicolor&amp;quot;, &amp;quot;virginica&amp;quot;)) # comparisons for post-hoc tests
# Edit until here


# Edit at your own risk
for (i in y) {
  for (j in x) {
    p &amp;lt;- ggboxplot(dat,
      x = colnames(dat[j]), y = colnames(dat[i]),
      color = colnames(dat[j]),
      legend = &amp;quot;none&amp;quot;,
      palette = &amp;quot;npg&amp;quot;,
      add = &amp;quot;jitter&amp;quot;
    )
    print(
      p + stat_compare_means(aes(label = paste0(after_stat(method), &amp;quot;, p-value = &amp;quot;, after_stat(p.format))),
        method = method1, label.y = max(dat[, i], na.rm = TRUE)
      )
      + stat_compare_means(comparisons = my_comparisons, method = method2, label = &amp;quot;p.format&amp;quot;) # remove if p-value of ANOVA or Kruskal-Wallis test &amp;gt;= alpha
    )
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-7-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-7-2.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-7-3.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-7-4.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Like the improved routine for the t-test, I have noticed that students and non-expert professionals understand ANOVA results presented this way much more easily compared to the default R outputs.&lt;/p&gt;
&lt;p&gt;With one graph for each variable, it is easy to see that all species are different from each other in terms of all 4 variables.&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;If you want to apply the same automated process to your data, you will need to modify the name of the grouping variable (&lt;code&gt;Species&lt;/code&gt;), the names of the variables you want to test (&lt;code&gt;Sepal.Length&lt;/code&gt;, etc.), whether you want to perform an &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;ANOVA&lt;/a&gt; (&lt;code&gt;anova&lt;/code&gt;) or &lt;a href=&#34;https://statsandr.com/blog/kruskal-wallis-test-nonparametric-version-anova/&#34;&gt;Kruskal-Wallis test&lt;/a&gt; (&lt;code&gt;kruskal.test&lt;/code&gt;) and finally specify the comparisons for the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#post-hoc-test&#34;&gt;post-hoc tests&lt;/a&gt;.&lt;a href=&#34;#fn4&#34; class=&#34;footnote-ref&#34; id=&#34;fnref4&#34;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;to-go-even-further&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;To go even further&lt;/h1&gt;
&lt;p&gt;As we have seen, these two improved R routines allow to:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Perform t-tests and ANOVA on a small or large number of variables with only minor changes to the code. I basically only have to replace the variable names and the name of the test I want to use. It takes almost the same time to test one or several variables so it is quite an improvement compared to testing one variable at a time.&lt;/li&gt;
&lt;li&gt;Share test results in a much proper and cleaner way. This is possible thanks to a graph showing the observations by group and the &lt;em&gt;p&lt;/em&gt;-value of the appropriate test included directly on the graph. This is particularly important when communicating results to a wider audience or to people from diverse backgrounds.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;However, like most of my R routines, these two pieces of code are still a work in progress. Below are some additional features I have been thinking of and which could be added in the future to make the process of comparing two or more groups even more optimal:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Add the possibility to select variables by their numbering in the dataframe. For the moment it is only possible to do it via their names. This will allow to automate the process even further because instead of typing all variable names one by one, we could simply type &lt;code&gt;4:25&lt;/code&gt; (to test variables 4 to 25 for instance).&lt;/li&gt;
&lt;li&gt;Add the possibility to choose a &lt;em&gt;p&lt;/em&gt;-value adjustment method. Currently, raw &lt;em&gt;p&lt;/em&gt;-values are displayed in the graphs and I manually adjust them afterwards or adjust the &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;When comparing more than two groups, it is only possible to apply an ANOVA or Kruskal-Wallis test at the moment. A major improvement would be to add the possibility to perform a repeated measures ANOVA (i.e., an ANOVA when the samples are dependent). It is currently already possible to do a t-test with two paired samples, but it is not yet possible to do the same with more than two groups.&lt;/li&gt;
&lt;li&gt;Another less important (yet still nice) feature when comparing more than 2 groups would be to automatically apply post-hoc tests only in the case where the null hypothesis of the ANOVA or Kruskal-Wallis test is rejected (so when there is at least one group different from the others, because if the null hypothesis of equal groups is not rejected we do not apply a post-hoc test). At the present time, I manually add or remove the code that displays the &lt;em&gt;p&lt;/em&gt;-values of post-hoc tests depending on the global &lt;em&gt;p&lt;/em&gt;-value of the ANOVA or Kruskal-Wallis test.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I will try to add these features in the future, or I would be glad to help if the author of the &lt;code&gt;{ggpubr}&lt;/code&gt; package needs help in including these features (I hope he will see this article!).&lt;/p&gt;
&lt;p&gt;Last but not least, the following packages may be of interest to some readers:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If you want to report statistical results on a graph, I advise you to check the &lt;a href=&#34;https://indrajeetpatil.github.io/ggstatsplot/&#34; target=&#34;_blank&#34;&gt;&lt;code&gt;{ggstatsplot}&lt;/code&gt; package&lt;/a&gt; and in particular the &lt;code&gt;ggbetweenstats()&lt;/code&gt; and &lt;code&gt;ggwithinstats()&lt;/code&gt; functions. These functions allow to compare a continuous variable across multiple groups or conditions (for both independent and paired samples). Two advantages of the functions is that:
&lt;ul&gt;
&lt;li&gt;it is very easy to switch from parametric to nonparametric tests and&lt;/li&gt;
&lt;li&gt;it automatically runs an ANOVA or t-test depending on the number of groups to compare&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that many different statistical results are displayed on the graph, not only the name of the test and the &lt;em&gt;p&lt;/em&gt;-value so a bit of simplicity and clarity is lost for more precision. However, it is still very convenient to be able to include tests results on a graph in order to combine the advantages of a visualization and a sound statistical analysis. Something that I still need to figure out is how to run the code on several variables at once.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The &lt;a href=&#34;https://cloud.r-project.org/web/packages/compareGroups/index.html&#34; target=&#34;_blank&#34;&gt;&lt;code&gt;{compareGroups}&lt;/code&gt; package&lt;/a&gt; also provides a nice way to compare groups. It comes with a really complete Shiny app, available with:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# install.packages(&amp;quot;compareGroups&amp;quot;)
library(compareGroups)
cGroupsWUI()&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;update-with-the-ggstatsplot-package&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Update with the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package&lt;/h1&gt;
&lt;p&gt;Several months after having written this article, I finally found a way to plot and run analyses on several variables at once with the package &lt;code&gt;{ggstatsplot}&lt;/code&gt; &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-patil2021ggstatsplot&#34;&gt;Patil 2021&lt;/a&gt;)&lt;/span&gt;. This was the main feature I was missing and which prevented me from using it more often.&lt;/p&gt;
&lt;p&gt;Although I still find that too much statistical details are displayed (in particular for non experts), I still believe the &lt;code&gt;ggbetweenstats()&lt;/code&gt; and &lt;code&gt;ggwithinstats()&lt;/code&gt; functions are worth mentioning in this article. I actually now use those two functions almost as often as my previous routines because:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;I do not have to care about the number of groups to compare, the functions automatically choose the appropriate test according to the number of groups (ANOVA for 3 groups or more, and t-test for 2 groups)&lt;/li&gt;
&lt;li&gt;I can select variables based on their column numbering, and not based on their names anymore (which prevents me from writing those variable names manually)&lt;/li&gt;
&lt;li&gt;When comparing 3 or more groups (so for ANOVA, Kruskal-Wallis, repeated measure ANOVA or Friedman), &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values of the post-hoc tests within each dependent variable are by default the adjusted &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values (Holm is the default but many adjustment methods are available)&lt;/li&gt;
&lt;li&gt;It is possible to compare both independent and paired samples, no matter the number of groups (remember that with the &lt;code&gt;ggpubr&lt;/code&gt; package I could only do paired samples for two samples, not for 3 samples)&lt;/li&gt;
&lt;li&gt;They allow to easily switch between the parametric and nonparametric version&lt;/li&gt;
&lt;li&gt;All this in a more concise manner using the &lt;code&gt;{purrr}&lt;/code&gt; package&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For those of you who are interested, below my updated R routine which include these functions and applied this time on the &lt;code&gt;penguins&lt;/code&gt; dataset.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(palmerpenguins)

dat &amp;lt;- penguins
str(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## tibble [344 × 8] (S3: tbl_df/tbl/data.frame)
##  $ species          : Factor w/ 3 levels &amp;quot;Adelie&amp;quot;,&amp;quot;Chinstrap&amp;quot;,..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ island           : Factor w/ 3 levels &amp;quot;Biscoe&amp;quot;,&amp;quot;Dream&amp;quot;,..: 3 3 3 3 3 3 3 3 3 3 ...
##  $ bill_length_mm   : num [1:344] 39.1 39.5 40.3 NA 36.7 39.3 38.9 39.2 34.1 42 ...
##  $ bill_depth_mm    : num [1:344] 18.7 17.4 18 NA 19.3 20.6 17.8 19.6 18.1 20.2 ...
##  $ flipper_length_mm: int [1:344] 181 186 195 NA 193 190 181 195 193 190 ...
##  $ body_mass_g      : int [1:344] 3750 3800 3250 NA 3450 3650 3625 4675 3475 4250 ...
##  $ sex              : Factor w/ 2 levels &amp;quot;female&amp;quot;,&amp;quot;male&amp;quot;: 2 1 1 NA 1 2 1 2 NA NA ...
##  $ year             : int [1:344] 2007 2007 2007 2007 2007 2007 2007 2007 2007 2007 ...&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We illustrate the routine for two groups with the variables &lt;code&gt;sex&lt;/code&gt; (two factors) as independent variable, and the 4 quantitative continuous variables &lt;code&gt;bill_length_mm&lt;/code&gt;, &lt;code&gt;bill_depth_mm&lt;/code&gt;, &lt;code&gt;flipper_length_mm&lt;/code&gt; and &lt;code&gt;body_mass_g&lt;/code&gt; as dependent variables:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggstatsplot)
library(tibble)

# Comparison between sexes

# edit from here
x &amp;lt;- &amp;quot;sex&amp;quot;
cols &amp;lt;- 3:6 # the 4 continuous dependent variables
type &amp;lt;- &amp;quot;parametric&amp;quot; # given the large number of observations, we use the parametric version
paired &amp;lt;- FALSE # FALSE for independent samples, TRUE for paired samples
# edit until here

# edit at your own risk
plotlist &amp;lt;-
  purrr::pmap(
    .l = list(
      data = list(as_tibble(dat)),
      x = x,
      y = as.list(colnames(dat)[cols]),
      plot.type = &amp;quot;box&amp;quot;, # for boxplot
      type = type, # parametric or nonparametric
      pairwise.comparisons = TRUE, # to run post-hoc tests if more than 2 groups
      pairwise.display = &amp;quot;significant&amp;quot;, # show only significant differences
      bf.message = FALSE, # remove message about Bayes Factor
      centrality.plotting = FALSE # remove central measure
    ),
    .f = ifelse(paired, # automatically use ggwithinstats if paired samples, ggbetweenstats otherwise
      ggstatsplot::ggwithinstats,
      ggstatsplot::ggbetweenstats
    ),
    violin.args = list(width = 0, linewidth = 0) # remove violin plots and keep only boxplots
  )

# print all plots together with statistical results
for (i in 1:length(plotlist)) {
  print(plotlist[[i]])
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-10-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-10-2.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-10-3.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-10-4.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;We now illustrate the routine for 3 groups or more with the variable &lt;code&gt;species&lt;/code&gt; (three factors) as independent variable, and the 4 same dependent variables:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Comparison between species

# edit from here
x &amp;lt;- &amp;quot;species&amp;quot;
cols &amp;lt;- 3:6 # the 4 continuous dependent variables
type &amp;lt;- &amp;quot;parametric&amp;quot; # given the large number of observations, we use the parametric version
paired &amp;lt;- FALSE # FALSE for independent samples, TRUE for paired samples
# edit until here

# edit at your own risk
plotlist &amp;lt;-
  purrr::pmap(
    .l = list(
      data = list(as_tibble(dat)),
      x = x,
      y = as.list(colnames(dat)[cols]),
      plot.type = &amp;quot;box&amp;quot;, # for boxplot
      type = type, # parametric or nonparametric
      pairwise.comparisons = TRUE, # to run post-hoc tests if more than 2 groups
      pairwise.display = &amp;quot;significant&amp;quot;, # show only significant differences
      bf.message = FALSE, # remove message about Bayes Factor
      centrality.plotting = FALSE # remove central measure
    ),
    .f = ifelse(paired, # automatically use ggwithinstats if paired samples, ggbetweenstats otherwise
      ggstatsplot::ggwithinstats,
      ggstatsplot::ggbetweenstats
    ),
    violin.args = list(width = 0, linewidth = 0) # remove violin plots and keep only boxplots
  )

# print all plots together with statistical results
for (i in 1:length(plotlist)) {
  print(plotlist[[i]])
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-11-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-11-2.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-11-3.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-19-how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way_files/figure-html/unnamed-chunk-11-4.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;As you can see, I only have to specify:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the name of the grouping variable (&lt;code&gt;sex&lt;/code&gt; and &lt;code&gt;species&lt;/code&gt;),&lt;/li&gt;
&lt;li&gt;the number of the dependent variables (variables 3 to 6 in the dataset),&lt;/li&gt;
&lt;li&gt;whether I want to use the parametric or nonparametric version and&lt;/li&gt;
&lt;li&gt;whether samples are independent (&lt;code&gt;paired = FALSE&lt;/code&gt;) or paired (&lt;code&gt;paired = TRUE&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Everything else is automated—the outputs show a graphical representation of what we are comparing, together with the details of the statistical analyses in the subtitle of the plot (the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value among others).&lt;/p&gt;
&lt;p&gt;Note that the code shown above is actually the same if I want to compare 2 groups or more than 2 groups. I wrote twice the same code (once for 2 groups and once again for 3 groups) for illustrative purposes only, but they are the same and should be treated as one for your projects.&lt;/p&gt;
&lt;!-- Feel free to discover the package and see how it works by yourself via this [Shiny app](https://antoinesoetewey.shinyapps.io/ggstatsplotShiny/){target=&#34;_blank&#34;}. --&gt;
&lt;p&gt;I must admit I am quite &lt;strong&gt;satisfied&lt;/strong&gt; with this routine, now that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;I can automate it on many variables at once and I do not need to write the variable names manually anymore,&lt;/li&gt;
&lt;li&gt;at the same time, I can choose the appropriate test among all the available ones (depending on the number of groups, whether they are paired or not, and whether I want to use the parametric or nonparametric version).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Nonetheless, I must also admit that I am still &lt;strong&gt;not satisfied&lt;/strong&gt; with the level of details of the statistical results. As already mentioned, many students get confused and get lost in front of so much information (except the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value and the number of observations, most of the details are rather obscure to them because they are not covered in introductory statistic classes).&lt;/p&gt;
&lt;p&gt;I saved time thanks to all improvements in comparison to my previous routine, but I definitely lose time when I have to point out to them what they should look for. After discussing with other professors, I noticed that they have the same problem.&lt;/p&gt;
&lt;p&gt;For the moment, you can only print all results or none. I have opened an &lt;a href=&#34;https://github.com/IndrajeetPatil/ggstatsplot/issues/669&#34; target=&#34;_blank&#34;&gt;issue&lt;/a&gt; kindly requesting to add the possibility to display only a summary (with the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value and the name of the test for instance).&lt;a href=&#34;#fn5&#34; class=&#34;footnote-ref&#34; id=&#34;fnref5&#34;&gt;&lt;sup&gt;5&lt;/sup&gt;&lt;/a&gt; I will update again this article if the maintainer of the package includes this feature in the future. So stay tuned!&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article will help you to perform t-tests and ANOVA for multiple variables at once and make the results more easily readable and interpretable by non-scientists. Learn more about the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;t-test&lt;/a&gt; to compare two groups, or the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;ANOVA&lt;/a&gt; to compare 3 groups or more.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-holm1979simple&#34; class=&#34;csl-entry&#34;&gt;
Holm, Sture. 1979. &lt;span&gt;“A Simple Sequentially Rejective Multiple Test Procedure.”&lt;/span&gt; &lt;em&gt;Scandinavian Journal of Statistics&lt;/em&gt;, 65–70.
&lt;/div&gt;
&lt;div id=&#34;ref-mcdonald2014multiple&#34; class=&#34;csl-entry&#34;&gt;
McDonald, JH. 2014. &lt;span&gt;“Multiple Tests.”&lt;/span&gt; &lt;em&gt;Handbook of Biological Statistics. 3rd Ed Baltimore, Maryland: Sparky House Publishing&lt;/em&gt;, 233–36.
&lt;/div&gt;
&lt;div id=&#34;ref-patil2021ggstatsplot&#34; class=&#34;csl-entry&#34;&gt;
Patil, Indrajeet. 2021. &lt;span&gt;“&lt;span class=&#34;nocase&#34;&gt;Visualizations with statistical details: The &lt;span class=&#34;nocase&#34;&gt;’ggstatsplot’&lt;/span&gt; approach&lt;/span&gt;.”&lt;/span&gt; &lt;em&gt;&lt;span class=&#34;nocase&#34;&gt;Journal of Open Source Software&lt;/span&gt;&lt;/em&gt; 6 (61): 3167. &lt;a href=&#34;https://doi.org/10.21105/joss.03167&#34;&gt;https://doi.org/10.21105/joss.03167&lt;/a&gt;.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;In theory, an ANOVA can also be used to compare two groups as it will give the same results compared to a Student’s t-test, but in practice we use the Student’s t-test to compare two groups and the ANOVA to compare three groups or more.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Do not forget to separate the variables you want to test with &lt;code&gt;|&lt;/code&gt;.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;Do not forget to adjust the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values or the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;. If you use the Bonferroni correction, the adjusted &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; is simply the desired &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; level divided by the number of comparisons.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;Post-hoc test is only the name used to refer to a specific type of statistical tests. Post-hoc test includes, among others, the Tukey HSD test, the Bonferroni correction, Dunnett’s test. Even if an ANOVA or a Kruskal-Wallis test can determine whether there is at least one group that is different from the others, it does not allow us to conclude &lt;strong&gt;which&lt;/strong&gt; are different from each other. For this purpose, there are post-hoc tests that compare all groups two by two to determine which ones are different, after adjusting for multiple comparisons. Concretely, post-hoc tests are performed to each possible pair of groups &lt;strong&gt;after&lt;/strong&gt; an ANOVA or a Kruskal-Wallis test has shown that there is at least one group which is different (hence “post” in the name of this type of test). The null and alternative hypotheses and the interpretations of these tests are similar to a Student’s t-test for two samples.&lt;a href=&#34;#fnref4&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn5&#34;&gt;&lt;p&gt;I am open to contribute to the package if I can help!&lt;a href=&#34;#fnref5&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>How to perform a one-sample t-test by hand and in R: test on one mean</title>
      <link>https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r-test-on-one-mean/</link>
      <pubDate>Mon, 09 Mar 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r-test-on-one-mean/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#null-and-alternative-hypothesis&#34; id=&#34;toc-null-and-alternative-hypothesis&#34;&gt;Null and alternative hypothesis&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#hypothesis-testing&#34; id=&#34;toc-hypothesis-testing&#34;&gt;Hypothesis testing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#two-versions-of-the-one-sample-t-test&#34; id=&#34;toc-two-versions-of-the-one-sample-t-test&#34;&gt;Two versions of the one-sample t-test&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#how-to-compute-the-one-sample-t-test-by-hand&#34; id=&#34;toc-how-to-compute-the-one-sample-t-test-by-hand&#34;&gt;How to compute the one-sample t-test by hand?&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-1-variance-of-the-population-is-known&#34; id=&#34;toc-scenario-1-variance-of-the-population-is-known&#34;&gt;Scenario 1: variance of the population is known&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-2-variance-of-the-population-is-unknown&#34; id=&#34;toc-scenario-2-variance-of-the-population-is-unknown&#34;&gt;Scenario 2: variance of the population is unknown&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#different-underlying-distributions-for-the-critical-value&#34; id=&#34;toc-different-underlying-distributions-for-the-critical-value&#34;&gt;Different underlying distributions for the critical value&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#how-to-compute-the-one-sample-t-test-in-r&#34; id=&#34;toc-how-to-compute-the-one-sample-t-test-in-r&#34;&gt;How to compute the one-sample t-test in R?&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-1-variance-of-the-population-is-known-1&#34; id=&#34;toc-scenario-1-variance-of-the-population-is-known-1&#34;&gt;Scenario 1: variance of the population is known&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-2-variance-of-the-population-is-unknown-1&#34; id=&#34;toc-scenario-2-variance-of-the-population-is-unknown-1&#34;&gt;Scenario 2: variance of the population is unknown&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#confidence-interval&#34; id=&#34;toc-confidence-interval&#34;&gt;Confidence interval&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#combination-of-plot-and-statistical-test&#34; id=&#34;toc-combination-of-plot-and-statistical-test&#34;&gt;Combination of plot and statistical test&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-2-variance-of-the-population-is-unknown-2&#34; id=&#34;toc-scenario-2-variance-of-the-population-is-unknown-2&#34;&gt;Scenario 2: variance of the population is unknown&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#assumptions&#34; id=&#34;toc-assumptions&#34;&gt;Assumptions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r_files/how-to-perform-a-one-sample-t-test-by-hand-and-in-r.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;After having written an article on the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test for two samples&lt;/a&gt; (independent and paired samples), I believe it is time to explain in details how to perform one-sample t-tests by hand and in R.&lt;/p&gt;
&lt;p&gt;One-sample t-test is an important part of inferential statistics (probably one of the first &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical test&lt;/a&gt; that students learn). Remind that, unlike &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics&lt;/a&gt;, inferential statistics is a branch of statistics aiming at drawing conclusions about one or two &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;populations&lt;/a&gt;, based on a subset (or two) of that population (called samples). In other words, we first collect a random set of observations from a population, and then some measurements are calculated in order to generalize to the population the information found through the sample.&lt;/p&gt;
&lt;p&gt;In this context, the &lt;strong&gt;one-sample t-test is used to determine whether the mean of a measurement variable is different from a specified value&lt;/strong&gt; (a belief or a theoretical expectation for example). It works as follows: if the mean of the sample is too distant from the specified value (the value under the null hypothesis), it is considered that the mean of the population is different from what is expected. On the contrary, if the mean of the sample is close to the specified value, we cannot reject the hypothesis that the population mean is equal to what is expected.&lt;/p&gt;
&lt;p&gt;Like the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test for two samples&lt;/a&gt; and the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;ANOVA&lt;/a&gt; (for 3 or more samples), there are also different versions of the one-sample t-test. Luckily, there are only two different versions for this test (the Student’s t-test for two samples has 5 versions!). The difference between the two versions of the one-sample t-test lies in the fact that one version is used when the variance of the &lt;em&gt;population&lt;/em&gt; (not the variance of the sample!) is known, the other version being used when the variance of the population is unknown.&lt;/p&gt;
&lt;p&gt;In this article, I will first detail step by step how to perform both versions of the one-sample t-test by hand. The analyses will be done on a small set of observations for the sake of illustration and easiness. I will then show how to perform this test in R with the exact same data in order to verify the results found by hand. Reminders about the reasoning behind &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt;, interpretations of the &lt;em&gt;p&lt;/em&gt;-value and the results, and assumptions of this test will also be presented.&lt;/p&gt;
&lt;p&gt;Note that the aim of this article is to show how to compute the one-sample t-test by hand and in R, so we refrain from testing the assumptions and we assume all assumptions are met for this exercise. For completeness, we still mention the assumptions and how to test them. Interested readers are invited to have a look at the &lt;a href=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r-test-on-one-mean/#assumptions&#34;&gt;end of the article&lt;/a&gt; for more information about these assumptions.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;null-and-alternative-hypothesis&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Null and alternative hypothesis&lt;/h1&gt;
&lt;p&gt;Before diving into the computations of the one-sample t-test by hand, let’s recap the null and alternative hypotheses of this test:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu = \mu_0\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu \ne \mu_0\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; is the population mean and &lt;span class=&#34;math inline&#34;&gt;\(\mu_0\)&lt;/span&gt; is the known or &lt;strong&gt;hypothesized&lt;/strong&gt; value of the mean in the population.&lt;/p&gt;
&lt;p&gt;This is in the general case where we simply want to determine whether the population mean is &lt;strong&gt;different&lt;/strong&gt; (in terms of the dependent variable) compared to the hypothesized value. In this sense, we have no prior belief about the population mean being larger or smaller than the hypothesized value. This type of test is referred as a &lt;strong&gt;two-sided&lt;/strong&gt; or bilateral test.&lt;/p&gt;
&lt;p&gt;If we have some prior beliefs about the population mean being larger or smaller than the hypothesized value, the one-sample t-test also allows to test the following hypotheses:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu = \mu_0\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu &amp;gt; \mu_0\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;or&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu = \mu_0\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu &amp;lt; \mu_0\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In the first case, we want to test if the population mean is significantly larger than the hypothesized value, while in the latter case, we want to test if the population mean is significantly smaller than the hypothesized value. This type of test is referred as a &lt;strong&gt;one-sided&lt;/strong&gt; or unilateral test.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;hypothesis-testing&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Hypothesis testing&lt;/h1&gt;
&lt;p&gt;In statistics, many statistical tests is in the form of &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt;. Hypothesis tests are used to determine whether a certain belief can be deemed as true (plausible) or not, based on the data at hand (i.e., the sample(s)). Most hypothesis tests boil down to the following 4 steps:&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;State the null and alternative hypothesis.&lt;/li&gt;
&lt;li&gt;Compute the test statistic, denoted t-stat. Formulas to compute the test statistic differ among the different versions of the one-sample t-test but they have the same structure. See scenarios 1 and 2 below to see the different formulas.&lt;/li&gt;
&lt;li&gt;Find the critical value given the theoretical statistical distribution of the test, the parameters of the distribution and the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;. For the two versions of the one-sample t-test, it is either the normal or the Student’s t distribution (&lt;em&gt;t&lt;/em&gt; denoting the Student distribution and &lt;em&gt;z&lt;/em&gt; denoting the normal distribution).&lt;/li&gt;
&lt;li&gt;Conclude by comparing the t-stat (found in step 2.) with the critical value (found in step. 3). If the t-stat lies in the rejection region (determined thanks to the critical value and the direction of the test), we reject the null hypothesis, otherwise we do not reject the null hypothesis. These two alternatives (reject or do not reject the null hypothesis) are the only two possible solutions, we never “accept” an hypothesis. It is also a good practice to always interpret the decision in the terms of the initial question.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;For the interested reader, see these 4 steps of hypothesis testing in more details in this &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;article&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;two-versions-of-the-one-sample-t-test&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Two versions of the one-sample t-test&lt;/h1&gt;
&lt;p&gt;There are two versions of the one-sample t-test, depending on whether the variance of the population (not the variance of the sample!) is known or unknown. This criteria is rather straightforward, we either know the variance of the population or we do not. The variance of the population cannot be computed because if you can compute the variance of a population, it means you have the data for the whole population, then there is no need to do a hypothesis test anymore…&lt;/p&gt;
&lt;p&gt;So the variance of the population is either given in the statement (use them in that case), or there is no information about the variance and in that case, it is assumed that the variance is unknown. In practice, the variance of the population is most of the time unknown. However, we still illustrate how to do both versions of this test by hand and in R in the next sections following the 4 steps of a hypothesis test.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;how-to-compute-the-one-sample-t-test-by-hand&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How to compute the one-sample t-test by hand?&lt;/h1&gt;
&lt;p&gt;Note that the data are artificial and do not represent any real variable. Furthermore, remind that the assumptions may or may not be met. The point of the article is to detail how to compute the different versions of the test by hand and in R, so all assumptions are assumed to be met. Moreover, we assume that for all tests the significance level, that is, the type I error is &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 5\)&lt;/span&gt;%.&lt;/p&gt;
&lt;p&gt;If you are interested in applying these tests by hand without having to do the computations yourself, here is a &lt;a href=&#34;https://statsandr.com/blog/a-shiny-app-for-inferential-statistics-by-hand/&#34;&gt;Shiny app&lt;/a&gt; which does it for you. You just need to enter the data and choose the appropriate version of the test thanks to the sidebar menu. There is also a graphical representation that helps you to visualize the test statistic and the rejection region. I hope you will find it useful!&lt;/p&gt;
&lt;div id=&#34;scenario-1-variance-of-the-population-is-known&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 1: variance of the population is known&lt;/h2&gt;
&lt;p&gt;For the first scenario, suppose the data below. Moreover, suppose that the population variance &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2 = 1\)&lt;/span&gt; and that we would like to test whether the population mean is different from 0.&lt;/p&gt;
&lt;table style=&#34;width:11%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;11%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt;value&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.9&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;-0.8&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1.3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;-0.3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1.7&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;So we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;5 observations: &lt;span class=&#34;math inline&#34;&gt;\(n = 5\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;mean of the sample: &lt;span class=&#34;math inline&#34;&gt;\(\bar{x} = 0.56\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;variance of the population: &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2 = 1\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\mu_0 = 0\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Following the 4 steps of hypothesis testing we have:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu = 0\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu \ne 0\)&lt;/span&gt;. (&lt;span class=&#34;math inline&#34;&gt;\(\ne\)&lt;/span&gt; because we want to test whether the population mean is different from 0, we do not impose a direction in the test.)&lt;/li&gt;
&lt;li&gt;Test statistic: &lt;span class=&#34;math display&#34;&gt;\[z_{obs} = \frac{\bar{x} - \mu_0}{\frac{\sigma}{\sqrt{n}}} = \frac{0.56-0}{0.447} = 1.252\]&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Critical value: &lt;span class=&#34;math inline&#34;&gt;\(\pm z_{\alpha / 2} = \pm z_{0.025} = \pm 1.96\)&lt;/span&gt; (see a guide on &lt;a href=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/&#34;&gt;how to read statistical tables&lt;/a&gt; if you struggle to find the critical value)&lt;/li&gt;
&lt;li&gt;Conclusion: The rejection regions are thus from &lt;span class=&#34;math inline&#34;&gt;\(-\infty\)&lt;/span&gt; to -1.96 and from 1.96 to &lt;span class=&#34;math inline&#34;&gt;\(+\infty\)&lt;/span&gt;. The test statistic is outside the rejection regions so we do not reject the null hypothesis &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;. In terms of the initial question: At the 5% significance level, we do not reject the hypothesis that the population mean is equal to 0, or there is no sufficient evidence in the data to conclude that the population mean is different from 0.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div id=&#34;scenario-2-variance-of-the-population-is-unknown&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 2: variance of the population is unknown&lt;/h2&gt;
&lt;p&gt;For the second scenario, suppose the data below. Moreover, suppose that the variance in the population is unknown and that we would like to test whether the population mean is larger than 5.&lt;/p&gt;
&lt;table style=&#34;width:11%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;11%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt;value&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;7.9&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;5.8&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;6.3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;7.3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;6.7&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;So we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;5 observations: &lt;span class=&#34;math inline&#34;&gt;\(n = 5\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;mean of the sample: &lt;span class=&#34;math inline&#34;&gt;\(\bar{x} = 6.8\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;standard deviation of the sample: &lt;span class=&#34;math inline&#34;&gt;\(s = 0.825\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\mu_0 = 5\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Following the 4 steps of hypothesis testing we have:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu = 5\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu &amp;gt; 5\)&lt;/span&gt;. (&amp;gt; because we want to test whether the population mean is larger than 5.)&lt;/li&gt;
&lt;li&gt;Test statistic: &lt;span class=&#34;math display&#34;&gt;\[t_{obs} = \frac{\bar{x} - \mu_0}{\frac{s}{\sqrt{n}}} = \frac{6.8-5}{0.369} = 4.881\]&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Critical value: &lt;span class=&#34;math inline&#34;&gt;\(t_{\alpha, n - 1} = t_{0.05, 4} = 2.132\)&lt;/span&gt; (see a guide on &lt;a href=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/&#34;&gt;how to read statistical tables&lt;/a&gt; if you struggle to find the critical value)&lt;/li&gt;
&lt;li&gt;Conclusion: The rejection region is thus from 2.132 to &lt;span class=&#34;math inline&#34;&gt;\(+\infty\)&lt;/span&gt;. The test statistic lies within the rejection region so we reject the null hypothesis &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;. In terms of the initial question: At the 5% significance level, we conclude that the population mean is larger than 5.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This concludes how to perform the two versions of the one-sample t-test by hand. In the next sections, we detail how to perform the exact same tests in R.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;different-underlying-distributions-for-the-critical-value&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Different underlying distributions for the critical value&lt;/h2&gt;
&lt;p&gt;As you may have noticed, the underlying probability distributions used to find the critical value are different depending on whether the variance of the population is known or unknown.&lt;/p&gt;
&lt;p&gt;The underlying probability distribution when the variance is known (scenario 1) is the normal distribution, while the probability distribution in the case where the variance is unknown (scenario 2) is the Student’s t distribution. This difference is partially explained by the fact that when the variance of the population is unknown, there is more “uncertainty” in the data, so we need to use the Student’s t distribution instead of the normal distribution.&lt;/p&gt;
&lt;p&gt;Note that when the sample size is large (usually when &lt;em&gt;n &amp;gt; 30&lt;/em&gt;), the Student’s t distribution tends to a normal distribution. Using a normal distribution when the variance is known and a Student’s t distribution when the variance is unknown also applies to a &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;t-test for two samples&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;how-to-compute-the-one-sample-t-test-in-r&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How to compute the one-sample t-test in R?&lt;/h1&gt;
&lt;p&gt;A good practice before doing t-tests in R is to visualize the data thanks to a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#boxplot&#34;&gt;boxplot&lt;/a&gt; (or eventually a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt; or a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#density-plot&#34;&gt;density plot&lt;/a&gt;). A boxplot gives a first indication on the location of the sample, and thus, a first indication on whether the null hypothesis is likely to be rejected or not. However, even if a boxplot or a density plot is great in showing the distribution of a sample, only a sound statistical test will confirm our first impression.&lt;/p&gt;
&lt;p&gt;After a visualization of the data, we replicate in R the results found by hand. Note that we use the same data, the same assumptions and the same question for both scenarios to facilitate the comparison between the tests performed by hand and in R.&lt;/p&gt;
&lt;div id=&#34;scenario-1-variance-of-the-population-is-known-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 1: variance of the population is known&lt;/h2&gt;
&lt;p&gt;For the first scenario, suppose the data below. Moreover, suppose that the population variance &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2 = 1\)&lt;/span&gt; and that we would like to test whether the population mean is different from 0.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat1 &amp;lt;- data.frame(
  value = c(0.9, -0.8, 1.3, -0.3, 1.7)
)

dat1&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   value
## 1   0.9
## 2  -0.8
## 3   1.3
## 4  -0.3
## 5   1.7&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggplot2)

ggplot(dat1) +
  aes(y = value) +
  geom_boxplot() +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r_files/figure-html/unnamed-chunk-3-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Note that you can use the &lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#esquisse&#34;&gt;&lt;code&gt;{esquisse}&lt;/code&gt; RStudio addin&lt;/a&gt; if you want to draw a boxplot with the &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;package &lt;code&gt;{ggplot2}&lt;/code&gt;&lt;/a&gt; without writing the code yourself. If you prefer the default graphics, use the &lt;code&gt;boxplot()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;boxplot(dat1$value)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r_files/figure-html/unnamed-chunk-4-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The boxplot shows that the distribution of the sample is not distant from 0 (the hypothesized value), so we tend to believe that we will not be able to reject the null hypothesis that the population mean is equal to 0. However, only a formal statistical test will confirm this belief.&lt;/p&gt;
&lt;p&gt;Below a function to perform a t-test with a known population variance, with arguments accepting the sample (&lt;code&gt;x&lt;/code&gt;), the variance of the population (&lt;code&gt;V&lt;/code&gt;), the mean under the null hypothesis (&lt;code&gt;m0&lt;/code&gt;, default is &lt;code&gt;0&lt;/code&gt;), the significance level (&lt;code&gt;alpha&lt;/code&gt;, default is &lt;code&gt;0.05&lt;/code&gt;) and the alternative (&lt;code&gt;alternative&lt;/code&gt;, one of &lt;code&gt;&#34;two.sided&#34;&lt;/code&gt; (default), &lt;code&gt;&#34;less&#34;&lt;/code&gt; or &lt;code&gt;&#34;greater&#34;&lt;/code&gt;):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;t.test2 &amp;lt;- function(x, V, m0 = 0, alpha = 0.05, alternative = &amp;quot;two.sided&amp;quot;) {
  M &amp;lt;- mean(x)
  n &amp;lt;- length(x)
  sigma &amp;lt;- sqrt(V)
  S &amp;lt;- sqrt(V / n)
  statistic &amp;lt;- (M - m0) / S
  p &amp;lt;- if (alternative == &amp;quot;two.sided&amp;quot;) {
    2 * pnorm(abs(statistic), lower.tail = FALSE)
  } else if (alternative == &amp;quot;less&amp;quot;) {
    pnorm(statistic, lower.tail = TRUE)
  } else {
    pnorm(statistic, lower.tail = FALSE)
  }
  LCL &amp;lt;- (M - S * qnorm(1 - alpha / 2))
  UCL &amp;lt;- (M + S * qnorm(1 - alpha / 2))
  value &amp;lt;- list(mean = M, m0 = m0, sigma = sigma, statistic = statistic, p.value = p, LCL = LCL, UCL = UCL, alternative = alternative)
  # print(sprintf(&amp;quot;P-value = %g&amp;quot;,p))
  # print(sprintf(&amp;quot;Lower %.2f%% Confidence Limit = %g&amp;quot;,
  #               alpha, LCL))
  # print(sprintf(&amp;quot;Upper %.2f%% Confidence Limit = %g&amp;quot;,
  #               alpha, UCL))
  return(value)
}

test &amp;lt;- t.test2(dat1$value,
  V = 1
)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $mean
## [1] 0.56
## 
## $m0
## [1] 0
## 
## $sigma
## [1] 1
## 
## $statistic
## [1] 1.252198
## 
## $p.value
## [1] 0.2104977
## 
## $LCL
## [1] -0.3165225
## 
## $UCL
## [1] 1.436523
## 
## $alternative
## [1] &amp;quot;two.sided&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output above recaps all the information needed to perform the test: the test statistic, the &lt;em&gt;p&lt;/em&gt;-value, the alternative used, the sample mean, the hypothesized value and the population variance (compare these results found in R with the results found by hand).&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value can be extracted as usual:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$p.value&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.2104977&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.21 so at the 5% significance level we do not reject the null hypothesis. There is no sufficient evidence in the data to reject the hypothesis that the population mean is equal to 0. This result confirms what we found by hand.&lt;/p&gt;
&lt;p&gt;Note that a similar function exists in the &lt;code&gt;{BSDA}&lt;/code&gt; package:&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(BSDA)

z.test(dat1$value,
  alternative = &amp;quot;two.sided&amp;quot;,
  mu = 0,
  sigma.x = 1,
  conf.level = 0.95
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	One-sample z-Test
## 
## data:  dat1$value
## z = 1.2522, p-value = 0.2105
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
##  -0.3165225  1.4365225
## sample estimates:
## mean of x 
##      0.56&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you are unfamiliar with the concept of &lt;em&gt;p&lt;/em&gt;-value, I invite you to read my &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/#a-note-on-p-value-and-significance-level-alpha&#34;&gt;note on &lt;em&gt;p&lt;/em&gt;-value and significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;To sum up&lt;/strong&gt; what have been said in that article about &lt;em&gt;p&lt;/em&gt;-value and significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If the &lt;em&gt;p&lt;/em&gt;-value is smaller than the predetermined significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; (usually 5%) so if &lt;em&gt;p&lt;/em&gt;-value &amp;lt; 0.05, we reject the null hypothesis&lt;/li&gt;
&lt;li&gt;If the &lt;em&gt;p&lt;/em&gt;-value is greater than or equal to the predetermined significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; (usually 5%) so if &lt;em&gt;p&lt;/em&gt;-value &lt;span class=&#34;math inline&#34;&gt;\(\ge\)&lt;/span&gt; 0.05, we do &lt;strong&gt;not reject&lt;/strong&gt; the null hypothesis&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This applies to all statistical tests without exception. Of course, the null and alternative hypotheses change depending on the test.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;scenario-2-variance-of-the-population-is-unknown-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 2: variance of the population is unknown&lt;/h2&gt;
&lt;p&gt;For the second scenario, suppose the data below. Moreover, suppose that the variance in the population is unknown and that we would like to test whether the population mean is larger than 5.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat2 &amp;lt;- data.frame(
  value = c(7.9, 5.8, 6.3, 7.3, 6.7)
)

dat2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   value
## 1   7.9
## 2   5.8
## 3   6.3
## 4   7.3
## 5   6.7&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat2) +
  aes(y = value) +
  geom_boxplot() +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r_files/figure-html/unnamed-chunk-8-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Unlike the previous scenario, the box is quite distant from the hypothesized value of 5. From this boxplot, we can expect the test to reject the null hypothesis of the population mean being equal to 5. Nonetheless, only a formal statistical test will confirm this expectation.&lt;/p&gt;
&lt;p&gt;There is a function in R, and it is simply the &lt;code&gt;t.test()&lt;/code&gt; function. This version of the test is actually the “standard” t-test for one-sample. Note that in our case the alternative hypothesis is &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu &amp;gt; 5\)&lt;/span&gt; so we need to add the arguments &lt;code&gt;mu = 5&lt;/code&gt; and &lt;code&gt;alternative = &#34;greater&#34;&lt;/code&gt; to the function because the default arguments are &lt;code&gt;mu = 0&lt;/code&gt; and the two-sided test:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- t.test(dat2$value,
  mu = 5,
  alternative = &amp;quot;greater&amp;quot;
)

test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	One Sample t-test
## 
## data:  dat2$value
## t = 4.8809, df = 4, p-value = 0.004078
## alternative hypothesis: true mean is greater than 5
## 95 percent confidence interval:
##  6.013814      Inf
## sample estimates:
## mean of x 
##       6.8&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output above recaps all the information needed to perform the test: the name of the test, the test statistic, the degrees of freedom, the &lt;em&gt;p&lt;/em&gt;-value, the alternative used, the hypothesized value and the sample mean (compare these results found in R with the results found by hand).&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value can be extracted as usual:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$p.value&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.004077555&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.004 so at the 5% significance level we reject the null hypothesis.&lt;/p&gt;
&lt;p&gt;Unlike the first scenario, the &lt;em&gt;p&lt;/em&gt;-value in this scenario is below 5% so we reject the null hypothesis. At the 5% significance level, we can conclude that the population mean is significantly larger than 5. This result confirms what we found by hand.&lt;/p&gt;
&lt;div id=&#34;confidence-interval&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Confidence interval&lt;/h3&gt;
&lt;p&gt;Note that the confidence interval can be extracted with &lt;code&gt;$conf.int&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$conf.int&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 6.013814      Inf
## attr(,&amp;quot;conf.level&amp;quot;)
## [1] 0.95&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can see that the 95% confidence interval for the population mean is &lt;span class=&#34;math inline&#34;&gt;\([6.01; \infty]\)&lt;/span&gt;, meaning that, at the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 5\)&lt;/span&gt;%, we reject the null hypothesis as long as the hypothesized value &lt;span class=&#34;math inline&#34;&gt;\(\mu_0\)&lt;/span&gt; is below 6.01, otherwise the null hypothesis cannot be rejected.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;combination-of-plot-and-statistical-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Combination of plot and statistical test&lt;/h2&gt;
&lt;p&gt;After having written this article, I discovered the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package which I believe is worth mentioning here, in particular the &lt;code&gt;gghistostats()&lt;/code&gt; function for one-sample Student’s t-test.&lt;/p&gt;
&lt;p&gt;This function combines a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt;—representing the distribution—and the results of the statistical test displayed in the subtitle of the plot.&lt;/p&gt;
&lt;p&gt;See examples below for scenario 2. Unfortunately, the package does not allow to run the test for scenario 1.&lt;/p&gt;
&lt;div id=&#34;scenario-2-variance-of-the-population-is-unknown-2&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Scenario 2: variance of the population is unknown&lt;/h3&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load packages
library(ggstatsplot)
library(ggplot2)

# plot with stat test
gghistostats(
  data = dat2, # dataframe from which variable is to be taken
  x = value, # numeric variable whose distribution is of interest
  type = &amp;quot;parametric&amp;quot;, # for student&amp;#39;s t-test
  test.value = 5 # default value is 0
) +
  labs(caption = NULL) # remove caption&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r_files/figure-html/unnamed-chunk-12-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is displayed after &lt;code&gt;p =&lt;/code&gt; in the subtitle of the plot. Based on this plot and the &lt;em&gt;p&lt;/em&gt;-value being lower than 5% (&lt;em&gt;p&lt;/em&gt;-value = 0.008), we reject the null hypothesis that the population mean is equal to 5.&lt;/p&gt;
&lt;p&gt;Note that, the &lt;em&gt;p&lt;/em&gt;-value is two times as large as the one obtained with the &lt;code&gt;t.test()&lt;/code&gt; function because when we ran &lt;code&gt;t.test()&lt;/code&gt; we specified &lt;code&gt;alternative = &#34;greater&#34;&lt;/code&gt; (i.e., a one-sided test). In our plot with the &lt;code&gt;gghistostats()&lt;/code&gt; function, it is a two-sided test that is performed by default, that is, &lt;code&gt;alternative = &#34;two.sided&#34;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The point of this section was to illustrate how to easily draw plots together with statistical results, which is exactly the aim of the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package. See more details and examples in this &lt;a href=&#34;https://statsandr.com/blog/how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way/&#34;&gt;article&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;assumptions&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Assumptions&lt;/h1&gt;
&lt;p&gt;As for many &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt;, there are some assumptions that need to be met in order to be able to interpret the results. When one or several assumptions are not met, although it is technically possible to perform these tests, it would be incorrect to interpret the results. Below are the assumptions of the one-sample t-test and how to test them:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Variable type&lt;/strong&gt;: The dependent variable (i.e., the measured variable) must be measured on a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#continuous&#34;&gt;continuous&lt;/a&gt; or &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#ordinal&#34;&gt;ordinal scale&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Independence&lt;/strong&gt;: The data, collected from a representative and randomly selected portion of the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;population&lt;/a&gt;, should be independent of one another. The assumption of independence is most often verified based on the design of the experiment and on the good control of experimental conditions rather than via a formal test. If you are still unsure about independence based on the experiment design, ask yourself if one observation is related to another (if one observation has an impact on another). If not, it is most likely that you have independent &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;samples&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Normality&lt;/strong&gt;:
&lt;ul&gt;
&lt;li&gt;With a small sample size (usually &lt;span class=&#34;math inline&#34;&gt;\(n &amp;lt; 30\)&lt;/span&gt;), observations should follow a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;&lt;strong&gt;normal distribution&lt;/strong&gt;&lt;/a&gt;. The normality assumption can be tested visually thanks to a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt; and a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#qq-plot&#34;&gt;QQ-plot&lt;/a&gt;, and/or formally via a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#normality-test&#34;&gt;normality test&lt;/a&gt; such as the Shapiro-Wilk or Kolmogorov-Smirnov test. Some transformations, such as among others, the logarithm, the square root or the Box-Cox transformation can be applied on the observations to transform you data to better fit the normal distribution. If, even after a transformation, your data still do not follow a normal distribution, the &lt;a href=&#34;https://statsandr.com/blog/one-sample-wilcoxon-test-in-r/&#34;&gt;one-sample Wilcoxon test&lt;/a&gt; (&lt;code&gt;wilcox.test(variable_name, data = dat&lt;/code&gt; in R) can be applied. This non-parametric test is robust to non normal distributions so it does not require normality of the data.&lt;/li&gt;
&lt;li&gt;With a large sample size (&lt;span class=&#34;math inline&#34;&gt;\(n \ge 30\)&lt;/span&gt;), &lt;strong&gt;normality of the data is not required&lt;/strong&gt; (this is a common misconception!). By the &lt;a href=&#34;https://en.wikipedia.org/wiki/Central_limit_theorem&#34; target=&#34;_blank&#34;&gt;central limit theorem&lt;/a&gt;, sample means of large samples are often well-approximated by a normal distribution even if the data are not normally distributed &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-stevens2013intermediate&#34;&gt;Stevens 2013&lt;/a&gt;)&lt;/span&gt;. It is therefore not required to test the normality assumption when the number of observations is large.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Outliers&lt;/strong&gt;: There should be no &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt; in your data. An observation slightly different from the others does not pose a problem, but it starts to be an issue when you have at least one &lt;em&gt;extreme&lt;/em&gt; outlier. In presence of at least one extreme outlier, it is best to transform your data (with the logarithm transformation for instance, as you would do with a non normal distribution) or use the non-parametric &lt;a href=&#34;https://statsandr.com/blog/one-sample-wilcoxon-test-in-r/&#34;&gt;one-sample Wilcoxon test&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to understand how the different versions of the one-sample t-test work and how to perform them by hand and in R.&lt;/p&gt;
&lt;p&gt;If you are interested, here is a &lt;a href=&#34;https://statsandr.com/blog/a-shiny-app-for-inferential-statistics-by-hand/&#34;&gt;Shiny app&lt;/a&gt; to perform these tests by hand easily (you just need to enter your data and select the appropriate version of the test thanks to the sidebar menu). Moreover, read &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;this article&lt;/a&gt; if you would like to know how to compute the Student’s t-test but this time, for two samples—in order to compare two dependent or independent groups—or this &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;article&lt;/a&gt; if you want to use an ANOVA to compare 3 or more groups.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-stevens2013intermediate&#34; class=&#34;csl-entry&#34;&gt;
Stevens, James P. 2013. &lt;em&gt;Intermediate Statistics: A Modern Approach&lt;/em&gt;. Routledge.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;It is a least the case regarding parametric hypothesis tests. A parametric test means that it is based on a theoretical statistical distribution, which depends on some defined parameters. In the case of the one-sample t-test, it is based on the Student’s t distribution with a single parameter, the degrees of freedom (&lt;span class=&#34;math inline&#34;&gt;\(df = n - 1\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is the sample size), or the normal distribution.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Thanks gmacar for pointing it out to me.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>The 9 concepts and formulas in probability that every data scientist should know</title>
      <link>https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/</link>
      <pubDate>Tue, 03 Mar 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#what-is-probability&#34; id=&#34;toc-what-is-probability&#34;&gt;What is probability?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#a-probability-is-always-between-0-and-1&#34; id=&#34;toc-a-probability-is-always-between-0-and-1&#34;&gt;1. A probability is always between 0 and 1&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#compute-a-probability&#34; id=&#34;toc-compute-a-probability&#34;&gt;2. Compute a probability&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#complement-of-an-event&#34; id=&#34;toc-complement-of-an-event&#34;&gt;3. Complement of an event&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#union-of-two-events&#34; id=&#34;toc-union-of-two-events&#34;&gt;4. Union of two events&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#intersection-of-two-events&#34; id=&#34;toc-intersection-of-two-events&#34;&gt;5. Intersection of two events&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#independence-of-two-events&#34; id=&#34;toc-independence-of-two-events&#34;&gt;6. Independence of two events&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conditional-probability&#34; id=&#34;toc-conditional-probability&#34;&gt;7. Conditional probability&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#bayes-theorem&#34; id=&#34;toc-bayes-theorem&#34;&gt;Bayes’ theorem&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#example&#34; id=&#34;toc-example&#34;&gt;Example&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#accuracy-measures&#34; id=&#34;toc-accuracy-measures&#34;&gt;8. Accuracy measures&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#false-negatives&#34; id=&#34;toc-false-negatives&#34;&gt;False negatives&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#false-positives&#34; id=&#34;toc-false-positives&#34;&gt;False positives&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#sensitivity&#34; id=&#34;toc-sensitivity&#34;&gt;Sensitivity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#specificity&#34; id=&#34;toc-specificity&#34;&gt;Specificity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#positive-predictive-value&#34; id=&#34;toc-positive-predictive-value&#34;&gt;Positive predictive value&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#negative-predictive-value&#34; id=&#34;toc-negative-predictive-value&#34;&gt;Negative predictive value&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#counting-techniques&#34; id=&#34;toc-counting-techniques&#34;&gt;9. Counting techniques&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#multiplication&#34; id=&#34;toc-multiplication&#34;&gt;Multiplication&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#example-1&#34; id=&#34;toc-example-1&#34;&gt;Example&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#permutation&#34; id=&#34;toc-permutation&#34;&gt;Permutation&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#example-2&#34; id=&#34;toc-example-2&#34;&gt;Example&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand&#34; id=&#34;toc-by-hand&#34;&gt;By hand&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#in-r&#34; id=&#34;toc-in-r&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#combination&#34; id=&#34;toc-combination&#34;&gt;Combination&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#example-3&#34; id=&#34;toc-example-3&#34;&gt;Example&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand-1&#34; id=&#34;toc-by-hand-1&#34;&gt;By hand&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#in-r-1&#34; id=&#34;toc-in-r-1&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/the-7-formulas-in-probability-that-every-data-scientist-should-know_files/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;what-is-probability&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;What is probability?&lt;/h1&gt;
&lt;p&gt;A probability is a number that reflects the &lt;strong&gt;chance that a particular event will occur&lt;/strong&gt;. In other words, it quantifies (on a scale from 0 to 1, or from 0% to 100%) &lt;strong&gt;how likely an event is to occur&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Probability is a branch of mathematics that provides models to describe random processes. These mathematical tools allow to establish theoretical models for random phenomena and to use them to make predictions. Like every model, the probabilistic model is a simplification of the world. However, the model is useful as soon as it captures the essential features.&lt;/p&gt;
&lt;p&gt;In this article, we present 9 fundamental formulas and concepts in probability that every data scientist should understand and master in order to appropriately handle any project involving probabilities.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;a-probability-is-always-between-0-and-1&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;1. A probability is always between 0 and 1&lt;/h1&gt;
&lt;p&gt;The probability of an event is always between 0 and 1 (or 0% and 100%). If we denote the probability that an event A (which could be any event) occurs by &lt;span class=&#34;math inline&#34;&gt;\(P(A)\)&lt;/span&gt;, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[0 \le P(A) \le 1\]&lt;/span&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If an event is impossible: &lt;span class=&#34;math inline&#34;&gt;\(P(A) = 0\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;If an event is certain: &lt;span class=&#34;math inline&#34;&gt;\(P(A) = 1\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For example, throwing a 7 with a standard six-sided dice (with faces ranging from 1 to 6) is impossible so its probability is equal to 0. Throwing head &lt;em&gt;or&lt;/em&gt; tail with a coin is certain, so its probability is equal to 1.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;compute-a-probability&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;2. Compute a probability&lt;/h1&gt;
&lt;p&gt;If the elements of a sample space (the set of all possible results of a randomized experiment) are equiprobable (= all elements have the same probability), then the probability of an event occurring is equal to the number of favourable cases (number of ways it can happen) divided by the number of possible cases (total number of outcomes):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A) = \frac{\text{number of favourable cases}}{\text{number of possible cases}}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For example, all numbers of a six-sided dice are equiprobable since they all have the same probability of occurring. The probability of rolling a 3 with a dice is thus&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(3) = \frac{\text{number of favourable cases}}{\text{number of possible cases}} = \frac{1}{6}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;because there is only one favourable case (there is only one face with a 3 on it), and there are 6 possible cases (because there are 6 faces altogether).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;complement-of-an-event&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;3. Complement of an event&lt;/h1&gt;
&lt;p&gt;The probability of the complement (or opposite) of an event is:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(\text{not A}) = P(\bar{A}) = 1 - P(A)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For instance, the probability of &lt;em&gt;not&lt;/em&gt; throwing a 3 with a dice is:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(\bar{A}) = 1 - P(A) = 1 - \frac{1}{6} = \frac{5}{6}\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;union-of-two-events&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;4. Union of two events&lt;/h1&gt;
&lt;p&gt;The probability of the union of two events is the probability of either occurring:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
P(\text{A or B)} &amp;amp;= P(A \cup B) \\
&amp;amp;= P(A) + P(B) - P(A \cap B)
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Suppose that the probability of a fire breaking out in two houses in a given year is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;in house A: 60%, so &lt;span class=&#34;math inline&#34;&gt;\(P(A) = 0.6\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;in house B: 45%, so &lt;span class=&#34;math inline&#34;&gt;\(P(B) = 0.45\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;in at least one of the two houses: 80%, so &lt;span class=&#34;math inline&#34;&gt;\(P(A \cup B) = 0.8\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Graphically we have&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/the-7-formulas-in-probability-that-every-data-scientist-should-know_files/figure-html/unnamed-chunk-1-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The probability of a fire breaking out in house A &lt;strong&gt;or&lt;/strong&gt; house B is&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A \cup B) = P(A) + P(B) - P(A \cap B)\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[= 0.6 + 0.45 - 0.25 = 0.8\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;By summing &lt;span class=&#34;math inline&#34;&gt;\(P(A)\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(P(B)\)&lt;/span&gt;, the intersection of A and B, i.e. &lt;span class=&#34;math inline&#34;&gt;\(P(A \cap B)\)&lt;/span&gt;, is counted twice. This is the reason we subtract it to count it only once.&lt;/p&gt;
&lt;p&gt;If two events are mutually exclusive (i.e., two events that cannot occur simultaneously), the probability of both events occurring &lt;span class=&#34;math inline&#34;&gt;\(P(A \cap B)\)&lt;/span&gt; is equal to 0, so the above formula becomes&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A \cup B) = P(A) + P(B)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For example, the event “rolling a 3” and the event “rolling a 6” on a six-sided dice are two mutually exclusive events since they cannot both occur at the same time. Since their joint probability is equal to 0, the probability of rolling a 3 or 6 on a six-sided dice is&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(3 \cup 6) = P(3) + P(6) = \frac{1}{6} + \frac{1}{6} = \frac{1}{3}\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;intersection-of-two-events&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;5. Intersection of two events&lt;/h1&gt;
&lt;p&gt;&lt;strong&gt;If two events are independent&lt;/strong&gt;, the probability of the intersection of the two events (i.e., the joint probability) is the probability of the two events occurring:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(\text{A and B)} = P(A \cap B) = P(A) \cdot P(B)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For instance, if two coins are flipped, the probability of both coins being tails is&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(T_1 \cap T_2) = P(T_1) \cdot P(T_2) = \frac{1}{2} \cdot \frac{1}{2} = \frac{1}{4}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(T_1\)&lt;/span&gt; (&lt;span class=&#34;math inline&#34;&gt;\(T_2\)&lt;/span&gt;) denotes the event that the first (second) coin is tail.&lt;/p&gt;
&lt;p&gt;Note that &lt;span class=&#34;math inline&#34;&gt;\(P(A \cap B) = P(B \cap A)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;If two events are mutually exclusive, their joint probability is equal to 0:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A \cap B) = 0\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;independence-of-two-events&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;6. Independence of two events&lt;/h1&gt;
&lt;p&gt;Another important concept in probability is the independence of two events. Formally, the events A and B are independent if and only if&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A \cap B) = P(A) \cdot P(B)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;If the equality holds, the two events are said to be independent, otherwise the two events are said to be dependent.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In the example of the two coins:&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(T_1 \cap T_2) = \frac{1}{4}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;and&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(T_1) \cdot P(T_2) = \frac{1}{2} \cdot \frac{1}{2} = \frac{1}{4}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;so the following equality holds&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(T_1 \cap T_2) = P(T_1) \cdot P(T_2) = \frac{1}{4}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The two events are thus independent, denoted &lt;span class=&#34;math inline&#34;&gt;\(T_1{\perp\!\!\!\perp}T_2\)&lt;/span&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In the example of the fire breaking out in two houses (see &lt;a href=&#34;https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/#union-of-two-events&#34;&gt;section 4&lt;/a&gt;):&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A \cap B) = 0.25\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;and&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A) \cdot P(B) = 0.6 \cdot 0.45 = 0.27\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;so the following equality does not hold&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A \cap B) \ne P(A) \cdot P(B)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The two events are thus dependent (or not independent), denoted &lt;span class=&#34;math inline&#34;&gt;\(A \not\!\perp\!\!\!\perp B\)&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conditional-probability&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;7. Conditional probability&lt;/h1&gt;
&lt;p&gt;Suppose two events A and B and &lt;span class=&#34;math inline&#34;&gt;\(P(B) &amp;gt; 0\)&lt;/span&gt;. The conditional probability of A given (knowing) B is the likelihood of event A occurring given that event B has occurred:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A | B) = \frac{P(A \cap B)}{P(B)}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[= \frac{P(B \cap A)}{P(B)} \text{ (since } P(A \cap B) = P(B \cap A))\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Note that, in general, the probability of A given B is not equal to the probability of B given A, that is, &lt;span class=&#34;math inline&#34;&gt;\(P(A | B) \ne P(B | A)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;From the formula of the conditional probability, we can derive the multiplicative law:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A | B) = \frac{P(A \cap B)}{P(B)} \text{ (Eq. 1)}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[P(A | B) \cdot P(B) = \frac{P(A \cap B)}{P(B)} \cdot P(B)\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[P(A | B) \cdot P(B) = P(A \cap B) \text{ (multiplicative law)}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;If two events are independent, &lt;span class=&#34;math inline&#34;&gt;\(P(A \cap B) = P(A) \cdot P(B)\)&lt;/span&gt;, and:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(P(B) &amp;gt; 0\)&lt;/span&gt;, the conditional probability becomes&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A | B) = \frac{P(A \cap B)}{P(B)}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[P(A | B) = \frac{P(A) \cdot P(B)}{P(B)}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[P(A | B) = P(A) \text{ (Eq. 2)}\]&lt;/span&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(P(A) &amp;gt; 0\)&lt;/span&gt;, the conditional probability becomes&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(B | A) = \frac{P(B \cap A)}{P(A)}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[P(B | A) = \frac{P(B) \cdot P(A)}{P(A)}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[P(B | A) = P(B) \text{ (Eq. 3)}\]&lt;/span&gt;
Equations 2 and 3 mean that knowing that one event occurred does not influence the probability of the outcome of the other event. This is in fact the definition of the independence: if knowing that one event occurred does not help to predict (does not influence) the outcome of the other event, the two events are by essence independent.&lt;/p&gt;
&lt;div id=&#34;bayes-theorem&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Bayes’ theorem&lt;/h2&gt;
&lt;p&gt;From the formulas of the conditional probability and the multiplicative law, we can derive the Bayes’ theorem:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
P(B | A) &amp;amp;= \frac{P(B \cap A)}{P(A)} \\
&amp;amp; \text{(from conditional probability)} \\
&amp;amp;= \frac{P(A \cap B)}{P(A)} \\
&amp;amp; \text{(since } P(A \cap B) = P(B \cap A)) \\
&amp;amp;= \frac{P(A | B) \cdot P(B)}{P(A)} \\
&amp;amp; \text{ (from multiplicative law)}
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;which is equivalent to&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
P(B | A) &amp;amp;= \frac{P(B | A) \cdot P(A)}{P(B)} \\
&amp;amp; \text{(Bayes&amp;#39; theorem)}
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;example&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Example&lt;/h2&gt;
&lt;p&gt;In order to illustrate the conditional probability and the Bayes’ theorem, suppose the following problem:&lt;/p&gt;
&lt;p&gt;In order to determine the presence of a disease in a person, a blood test is performed. When a person has the disease, the test can reveal the disease in 80% of cases. When the disease is not present, the test is negative in 90% of cases. Experience has shown that the probability of the disease being present is 10%. A researcher would like to know the probability that an individual has the disease &lt;em&gt;given that the result of the test is positive&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;To answer this question, the following events are defined:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;P: the test result is positive&lt;/li&gt;
&lt;li&gt;D: the person has the disease&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Moreover, we use a tree diagram to illustrate the statement:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/the-7-formulas-in-probability-that-every-data-scientist-should-know_files/Screenshot%202020-03-03%20at%2013.54.24.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;(The sum of all 4 scenarios must be equal to 1 since these 4 scenarios cover all possible cases.)&lt;/p&gt;
&lt;p&gt;We are looking for the probability that an individual has the disease given that the result of the test is positive, &lt;span class=&#34;math inline&#34;&gt;\(P(D | P)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Following the formula of the conditional probability (Eq. 1) we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A | B) = \frac{P(A \cap B)}{P(B)}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In terms of our problem:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(D | P) = \frac{P(D \cap P)}{P(P)}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[P(D | P) = \frac{0.08}{P(P)} \text{ (Eq. 4)}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;From the tree diagram, we can see that a positive test result is possible under two scenarios:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;when a person has the disease, or&lt;/li&gt;
&lt;li&gt;when the person does not actually have the disease (because the test is not always correct).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In order to find the probability of a positive test result, &lt;span class=&#34;math inline&#34;&gt;\(P(P)\)&lt;/span&gt;, we need to sum up those two scenarios:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
P(P) &amp;amp;= P(D \cap P) + P(\bar{D} \cap P) \\
&amp;amp;= 0.08 + 0.09 \\
&amp;amp;= 0.17
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Eq. 4 then becomes&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(D | P) = \frac{0.08}{0.17} = 0.4706\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The probability of having the disease given that the result of the test is positive is only 47.06%. This means that in this specific case (with the same percentages), an individual with a positive test has less than 1 chance out of 2 of having the disease!&lt;/p&gt;
&lt;p&gt;This relatively small percentage is due to the facts that the disease is quite rare (only 10% of the population is affected) and that the test is not always correct (sometimes it detects the disease although it is not present, and sometimes it does not detect it although it is present).&lt;/p&gt;
&lt;p&gt;As a consequence, a higher percentage of healthy people have a positive result (9%) compared to the percentage of people who have a positive result and who actually have the disease (8%). This explains why several diagnostic tests are often performed before announcing the diagnosis, especially for rare diseases.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;accuracy-measures&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;8. Accuracy measures&lt;/h1&gt;
&lt;p&gt;Based on the example of the disease and the diagnostic test presented above, we explain the most common accuracy measures:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;False negative (number and rate)&lt;/li&gt;
&lt;li&gt;False positive (number and rate)&lt;/li&gt;
&lt;li&gt;Sensitivity&lt;/li&gt;
&lt;li&gt;Specificity&lt;/li&gt;
&lt;li&gt;Positive predictive value&lt;/li&gt;
&lt;li&gt;Negative predictive value&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Before diving into the details of these accuracy measures, here is an overview of the measures and the tree diagram with the labels added for each of the 4 scenarios:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/the-7-formulas-in-probability-that-every-data-scientist-should-know_files/the-7-concepts-and-formulas-in-probability-that-every-data-scientist-should-know.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Adapted from Wikipedia&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/the-7-formulas-in-probability-that-every-data-scientist-should-know_files/Screenshot%202020-03-03%20at%2015.53.19.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;false-negatives&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;False negatives&lt;/h2&gt;
&lt;p&gt;The false negatives (FN) are the number of people incorrectly labeled as &lt;strong&gt;not&lt;/strong&gt; having the disease or the condition, when in reality it is present. It is like telling a women who is 7 months pregnant that she is not pregnant.&lt;/p&gt;
&lt;p&gt;From the tree diagram, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[FN = P(D \cap \bar{P}) = 0.02\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Moreover, the false negative &lt;strong&gt;rate&lt;/strong&gt; (&lt;em&gt;FNR&lt;/em&gt;) is defined as&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
FNR &amp;amp;= \frac{FN}{FN + TP} \\
&amp;amp;= P(\bar{P} | D) \\
&amp;amp;= \frac{P(\bar{P} \cap D)}{P(D)} \\
&amp;amp;= \frac{0.02}{0.08 + 0.02} \\
&amp;amp;= 0.2
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;false-positives&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;False positives&lt;/h2&gt;
&lt;p&gt;The false positives (FP) are the number of people incorrectly labeled as having the disease or the condition, when in reality it is &lt;strong&gt;not&lt;/strong&gt; present. It is like telling a man he is pregnant.&lt;/p&gt;
&lt;p&gt;From the tree diagram, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[FP = P(\bar{D} \cap P) = 0.09\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Moreover, the false positive &lt;strong&gt;rate&lt;/strong&gt; (&lt;em&gt;FPR&lt;/em&gt;) is defined as&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
FPR &amp;amp;= \frac{FP}{FP + TN} \\
&amp;amp;= P(P | \bar{D}) \\
&amp;amp;= \frac{P(P \cap \bar{D})}{P(\bar{D})} \\
&amp;amp;= \frac{0.09}{0.09 + 0.81} \\
&amp;amp;= 0.1
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;sensitivity&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Sensitivity&lt;/h2&gt;
&lt;p&gt;The sensitivity of a test, also referred as the recall, measures the ability of a test to detect the condition when the condition is present (the percentage of sick people who are correctly identified as having the disease):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[ Sensitivity = \frac{TP}{TP + FN}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;em&gt;TP&lt;/em&gt; is the true positives.&lt;/p&gt;
&lt;p&gt;From the tree diagram, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
Sensitivity &amp;amp;= \frac{TP}{TP + FN} \\
&amp;amp;= P(P|D) \\
&amp;amp;= 0.8
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Note also that &lt;span class=&#34;math inline&#34;&gt;\(1 - sensitivity = FNR\)&lt;/span&gt; (false negative rate).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;specificity&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Specificity&lt;/h2&gt;
&lt;p&gt;The specificity of a test measures the ability of a test to correctly exclude the condition when the condition is absent (the percentage of healthy people who are correctly identified as not having the disease):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[Specificity = \frac{TN}{TN + FP}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;em&gt;TN&lt;/em&gt; is the true negatives.&lt;/p&gt;
&lt;p&gt;From the tree diagram, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
Specificity &amp;amp;= \frac{TN}{TN + FP} \\
&amp;amp;= P(\bar{P} | \bar{D}) \\
&amp;amp;= 0.9
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Note also that &lt;span class=&#34;math inline&#34;&gt;\(1 - specificity = FPR\)&lt;/span&gt; (false positive rate).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;positive-predictive-value&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Positive predictive value&lt;/h2&gt;
&lt;p&gt;The positive predictive value, also referred as the precision, is the proportion of positives that correspond to the presence of the condition, so the proportions of positive results that are true positive results:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[PPV = \frac{TP}{TP+FP}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;From the tree diagram, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
PPV &amp;amp;= \frac{TP}{TP+FP} \\
&amp;amp;= P(D | P) \\
&amp;amp;= \frac{P(D \cap P)}{P(P)} \\
&amp;amp;= \frac{0.08}{0.08+0.09} \\
&amp;amp;= 0.4706
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;negative-predictive-value&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Negative predictive value&lt;/h2&gt;
&lt;p&gt;The negative predictive value is the proportion of negatives that correspond to the absence of the condition, so the proportions of negative results that are true negative results:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[NPV = \frac{TN}{TN + FN}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;From the tree diagram, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
NPV &amp;amp;= \frac{TN}{TN + FN} \\
&amp;amp;= P(\bar{D} | \bar{P}) \\
&amp;amp;= \frac{P(\bar{D} \cap \bar{P})}{P(\bar{P})} \\
&amp;amp;= \frac{0.81}{0.81+0.02} \\
&amp;amp;= 0.9759
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;counting-techniques&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;9. Counting techniques&lt;/h1&gt;
&lt;p&gt;In order to use the formula in &lt;a href=&#34;https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/#compute-a-probability&#34;&gt;section 2&lt;/a&gt;, one must know how to count the number of possible elements (both for favorable and possible cases).&lt;/p&gt;
&lt;p&gt;There are 3 main counting techniques in probability:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Multiplication&lt;/li&gt;
&lt;li&gt;Permutation&lt;/li&gt;
&lt;li&gt;Combination&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;See below how to count the number of possible elements in case of equiprobable results.&lt;/p&gt;
&lt;div id=&#34;multiplication&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Multiplication&lt;/h2&gt;
&lt;p&gt;The multiplication rule is as follows:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\#(A \times B) = (\#A) \times (\#B)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(\#\)&lt;/span&gt; is the number of elements.&lt;/p&gt;
&lt;div id=&#34;example-1&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Example&lt;/h3&gt;
&lt;p&gt;In a restaurant, a customer has to choose a starter, a main course and a dessert. The restaurant offers 2 starters, 3 main courses and 2 desserts. How many different choices are possible?&lt;/p&gt;
&lt;p&gt;There are &lt;span class=&#34;math inline&#34;&gt;\(2 \cdot 3 \cdot 2 = 12\)&lt;/span&gt; different possible choices.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;permutation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Permutation&lt;/h2&gt;
&lt;p&gt;The number of permutations is as follows:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
P^r_n &amp;amp;= n \times (n - 1) \times \cdots \times (n - r + 1) \\
&amp;amp;= \frac{n !}{(n - r)!}
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;with &lt;span class=&#34;math inline&#34;&gt;\(r\)&lt;/span&gt; the length, &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; the number of elements and &lt;span class=&#34;math inline&#34;&gt;\(r \le n\)&lt;/span&gt;. Note that &lt;span class=&#34;math inline&#34;&gt;\(0! = 1\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(k! = k \times (k - 1) \times (k - 2) \times \cdots \times 2 \times 1\)&lt;/span&gt; if &lt;span class=&#34;math inline&#34;&gt;\(k = 1, 2, \dots\)&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The order is important in permutations!&lt;/p&gt;
&lt;div id=&#34;example-2&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Example&lt;/h3&gt;
&lt;p&gt;Count the permutations of length 2 of the set &lt;span class=&#34;math inline&#34;&gt;\(A = \{a, b, c, d\}\)&lt;/span&gt;, without a letter being repeated. How many permutations do you find?&lt;/p&gt;
&lt;div id=&#34;by-hand&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;By hand&lt;/h4&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P^4_2 = \frac{4!}{(4-2)!} = \frac{4\cdot3\cdot2\cdot1}{2\cdot1} = 12\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;In R&lt;/h4&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(gtools)

x &amp;lt;- c(&amp;quot;a&amp;quot;, &amp;quot;b&amp;quot;, &amp;quot;c&amp;quot;, &amp;quot;d&amp;quot;)

# See all different permutations
perms &amp;lt;- permutations(
  n = 4, r = 2, v = x,
  repeats.allowed = FALSE
)
perms&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       [,1] [,2]
##  [1,] &amp;quot;a&amp;quot;  &amp;quot;b&amp;quot; 
##  [2,] &amp;quot;a&amp;quot;  &amp;quot;c&amp;quot; 
##  [3,] &amp;quot;a&amp;quot;  &amp;quot;d&amp;quot; 
##  [4,] &amp;quot;b&amp;quot;  &amp;quot;a&amp;quot; 
##  [5,] &amp;quot;b&amp;quot;  &amp;quot;c&amp;quot; 
##  [6,] &amp;quot;b&amp;quot;  &amp;quot;d&amp;quot; 
##  [7,] &amp;quot;c&amp;quot;  &amp;quot;a&amp;quot; 
##  [8,] &amp;quot;c&amp;quot;  &amp;quot;b&amp;quot; 
##  [9,] &amp;quot;c&amp;quot;  &amp;quot;d&amp;quot; 
## [10,] &amp;quot;d&amp;quot;  &amp;quot;a&amp;quot; 
## [11,] &amp;quot;d&amp;quot;  &amp;quot;b&amp;quot; 
## [12,] &amp;quot;d&amp;quot;  &amp;quot;c&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Count the number of permutations
nrow(perms)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 12&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;combination&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Combination&lt;/h2&gt;
&lt;p&gt;The number of combinations is as follows:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
C^r_n &amp;amp;= \frac{P^r_n}{r!} \\
&amp;amp;= \frac{n !}{r!(n - r)!} \\
&amp;amp;= {n \choose r} \\
&amp;amp;= \frac{n}{r} \times \frac{n - 1}{r - 1} \times \dots \times \frac{n - r + 1}{1}
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;with &lt;span class=&#34;math inline&#34;&gt;\(r\)&lt;/span&gt; the length, &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; the number of elements and &lt;span class=&#34;math inline&#34;&gt;\(r \le n\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;The order is &lt;strong&gt;not&lt;/strong&gt; important in combinations!&lt;/p&gt;
&lt;div id=&#34;example-3&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Example&lt;/h3&gt;
&lt;p&gt;In a family of 5 children, what is the probability that there are 3 girls and 2 boys? Assume that the probabilities of giving birth to a girl and a boy are equal.&lt;/p&gt;
&lt;div id=&#34;by-hand-1&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;By hand&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Count of 3 girls and 2 boys (favourable cases): &lt;span class=&#34;math inline&#34;&gt;\(C^3_5 = {5 \choose 3} = \frac{5!}{3!(5-3)!} = 10\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Count of possible cases: &lt;span class=&#34;math inline&#34;&gt;\(2^5 = 32\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(\Rightarrow P(3 \text{ girls and 2 boys}) = \frac{\text{# of favourable cases}}{\text{# of possible cases}}\)&lt;/span&gt; &lt;span class=&#34;math display&#34;&gt;\[= \frac{10}{32} = 0.3125\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r-1&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;In R&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Count of 3 girls and 2 boys:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;choose(n = 5, k = 3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 10&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;Count of possible cases:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;2^5&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 32&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Probability of 3 girls and 2 boys:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;choose(n = 5, k = 3) / 2^5&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.3125&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to understand the most important formulas and concepts from probability theory.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Student&#39;s t-test in R and by hand: how to compare two groups under different scenarios?</title>
      <link>https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/</link>
      <pubDate>Fri, 28 Feb 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/</guid>
      <description>
&lt;script src=&#34;https://statsandr.com/rmarkdown-libs/htmlwidgets/htmlwidgets.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;https://statsandr.com/rmarkdown-libs/viz/viz.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;https://statsandr.com/rmarkdown-libs/DiagrammeR-styles/styles.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/rmarkdown-libs/grViz-binding/grViz.js&#34;&gt;&lt;/script&gt;

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#null-and-alternative-hypothesis&#34; id=&#34;toc-null-and-alternative-hypothesis&#34;&gt;Null and alternative hypothesis&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#hypothesis-testing&#34; id=&#34;toc-hypothesis-testing&#34;&gt;Hypothesis testing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#different-versions-of-the-students-t-test&#34; id=&#34;toc-different-versions-of-the-students-t-test&#34;&gt;Different versions of the Student’s t-test&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#how-to-compute-students-t-test-by-hand&#34; id=&#34;toc-how-to-compute-students-t-test-by-hand&#34;&gt;How to compute Student’s t-test by hand?&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-1-independent-samples-with-2-known-variances&#34; id=&#34;toc-scenario-1-independent-samples-with-2-known-variances&#34;&gt;Scenario 1: Independent samples with 2 known variances&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-2-independent-samples-with-2-equal-but-unknown-variances&#34; id=&#34;toc-scenario-2-independent-samples-with-2-equal-but-unknown-variances&#34;&gt;Scenario 2: Independent samples with 2 equal but unknown variances&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-3-independent-samples-with-2-unequal-and-unknown-variances&#34; id=&#34;toc-scenario-3-independent-samples-with-2-unequal-and-unknown-variances&#34;&gt;Scenario 3: Independent samples with 2 unequal and unknown variances&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-4-paired-samples-where-the-variance-of-the-differences-is-known&#34; id=&#34;toc-scenario-4-paired-samples-where-the-variance-of-the-differences-is-known&#34;&gt;Scenario 4: Paired samples where the variance of the differences is known&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-5-paired-samples-where-the-variance-of-the-differences-is-unknown&#34; id=&#34;toc-scenario-5-paired-samples-where-the-variance-of-the-differences-is-unknown&#34;&gt;Scenario 5: Paired samples where the variance of the differences is unknown&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#how-to-compute-students-t-test-in-r&#34; id=&#34;toc-how-to-compute-students-t-test-in-r&#34;&gt;How to compute Student’s t-test in R?&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-1-independent-samples-with-2-known-variances-1&#34; id=&#34;toc-scenario-1-independent-samples-with-2-known-variances-1&#34;&gt;Scenario 1: Independent samples with 2 known variances&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#a-note-on-p-value-and-significance-level-alpha&#34; id=&#34;toc-a-note-on-p-value-and-significance-level-alpha&#34;&gt;A note on &lt;em&gt;p&lt;/em&gt;-value and significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-2-independent-samples-with-2-equal-but-unknown-variances-1&#34; id=&#34;toc-scenario-2-independent-samples-with-2-equal-but-unknown-variances-1&#34;&gt;Scenario 2: Independent samples with 2 equal but unknown variances&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-3-independent-samples-with-2-unequal-and-unknown-variances-1&#34; id=&#34;toc-scenario-3-independent-samples-with-2-unequal-and-unknown-variances-1&#34;&gt;Scenario 3: Independent samples with 2 unequal and unknown variances&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-4-paired-samples-where-the-variance-of-the-differences-is-known-1&#34; id=&#34;toc-scenario-4-paired-samples-where-the-variance-of-the-differences-is-known-1&#34;&gt;Scenario 4: Paired samples where the variance of the differences is known&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-5-paired-samples-where-the-variance-of-the-differences-is-unknown-1&#34; id=&#34;toc-scenario-5-paired-samples-where-the-variance-of-the-differences-is-unknown-1&#34;&gt;Scenario 5: Paired samples where the variance of the differences is unknown&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#combination-of-plot-and-statistical-test&#34; id=&#34;toc-combination-of-plot-and-statistical-test&#34;&gt;Combination of plot and statistical test&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-2-independent-samples-with-2-equal-but-unknown-variances-2&#34; id=&#34;toc-scenario-2-independent-samples-with-2-equal-but-unknown-variances-2&#34;&gt;Scenario 2: Independent samples with 2 equal but unknown variances&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-3-independent-samples-with-2-unequal-and-unknown-variances-2&#34; id=&#34;toc-scenario-3-independent-samples-with-2-unequal-and-unknown-variances-2&#34;&gt;Scenario 3: Independent samples with 2 unequal and unknown variances&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-5-paired-samples-where-the-variance-of-the-differences-is-unknown-2&#34; id=&#34;toc-scenario-5-paired-samples-where-the-variance-of-the-differences-is-unknown-2&#34;&gt;Scenario 5: Paired samples where the variance of the differences is unknown&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#assumptions&#34; id=&#34;toc-assumptions&#34;&gt;Assumptions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios_files/Student-t-test-in-R-and-by-hand-how-to-compare-two-groups-under-different-scenarios.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;One of the most important test within the branch of inferential statistics is the &lt;strong&gt;Student’s t-test&lt;/strong&gt;.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; The Student’s t-test for two samples is used to &lt;strong&gt;test whether two groups (two populations) are different&lt;/strong&gt; in terms of a quantitative variable, &lt;strong&gt;based on the comparison of two samples&lt;/strong&gt; drawn from these two groups. In other words, a Student’s t-test for two samples allows to determine whether the two populations from which your two samples are drawn are different (with the two samples being measured on a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#continuous&#34;&gt;quantitative continuous&lt;/a&gt; variable).&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The reasoning behind this &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical test&lt;/a&gt; is that if your two samples are markedly different from each other, it can be assumed that the two populations from which the samples are drawn are different. On the contrary, if the two samples are rather similar, we cannot reject the hypothesis that the two populations are similar, so there is no sufficient evidence in the data at hand to conclude that the two populations from which the samples are drawn are different. Note that this statistical tool belongs to the branch of inferential statistics because conclusions drawn from the study of the samples are generalized to the population, even though we do not have the data on the entire population.&lt;/p&gt;
&lt;p&gt;To compare two samples, it is usual to compare a measure of central tendency computed for each sample. In the case of the Student’s t-test, the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#mean&#34;&gt;mean&lt;/a&gt; is used to compare the two samples. However, in some cases, the mean is not appropriate to compare two samples so the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#median&#34;&gt;median&lt;/a&gt; is used to compare them via the &lt;a href=&#34;https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/&#34;&gt;Wilcoxon test&lt;/a&gt;. This article being already quite long and complete, the Wilcoxon test is covered in a separate &lt;a href=&#34;https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/&#34;&gt;article&lt;/a&gt;, together with some illustrations on when to use one test or the other.&lt;/p&gt;
&lt;p&gt;These two tests (Student’s t-test and Wilcoxon test) have the same final goal, that is, compare two samples in order to determine whether the two populations from which they were drawn are different or not. Note that the Student’s t-test is more powerful than the Wilcoxon test (i.e., it more often detects a significant difference if there is a true difference, so a smaller difference can be detected with the Student’s t-test) but the Student’s t-test is sensitive to &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt; and data asymmetry. Furthermore, within each of these two tests, several versions exist, with each version using different formulas to arrive at the final result. It is thus necessary to understand the difference between the two tests and which version to use in order to carry out the appropriate analyses depending on the question and the data at hand.&lt;/p&gt;
&lt;p&gt;In this article, I will first detail step by step how to perform all versions of the Student’s t-test for independent and paired samples by hand. The analyses will be done on a small set of observations for the sake of illustration and easiness. I will then show how to perform this test in R with the exact same data in order to verify the results found by hand. Reminders about the reasoning behind &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis testing&lt;/a&gt;, interpretations of the &lt;em&gt;p&lt;/em&gt;-value and the results, and assumptions of this test will also be presented.&lt;/p&gt;
&lt;p&gt;Note that the aim of this article is to show how to compute the Student’s t-test by hand and in R, so we refrain from testing the assumptions and we assume all of them are met for this exercise. For completeness, we still mention the assumptions, how to test them and what other tests exist if one is not met. Interested readers are invited to have a look at the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/#assumptions&#34;&gt;end of the article&lt;/a&gt; for more information about these assumptions.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;null-and-alternative-hypothesis&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Null and alternative hypothesis&lt;/h1&gt;
&lt;p&gt;Before diving into the computations of the Student’s t-test by hand, let’s recap the null and alternative hypotheses of this test:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu_1 = \mu_2\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu_1 \ne \mu_2\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(\mu_1\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\mu_2\)&lt;/span&gt; are the means of the two populations from which the samples were drawn.&lt;/p&gt;
&lt;p&gt;As mentioned in the introduction, although technically the Student’s t-test is based on the comparison of the means of the two samples, the final goal of this test is actually to test the following hypotheses:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: the two populations are similar&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: the two populations are different&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This is in the general case where we simply want to determine whether the two populations are &lt;strong&gt;different&lt;/strong&gt; or not (in terms of the dependent variable). In this sense, we have no prior belief about a particular population mean being larger or smaller than the other. This type of test is referred as a &lt;strong&gt;two-sided&lt;/strong&gt; or bilateral test.&lt;/p&gt;
&lt;p&gt;If we have some prior beliefs about one population mean being larger or smaller than the other, the Student’s t-test also allows to test the following hypotheses:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu_1 = \mu_2\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu_1 &amp;gt; \mu_2\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;or&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu_1 = \mu_2\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu_1 &amp;lt; \mu_2\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In the first case, we want to test if the mean of the first population is significantly larger than the mean of the second, while in the latter case, we want to test if the mean of the first population is significantly smaller than the mean of the second. This type of test is referred as a &lt;strong&gt;one-sided&lt;/strong&gt; or unilateral test.&lt;/p&gt;
&lt;p&gt;Some authors argue that one-sided tests should not be used in practice for the simple reason that, if a researcher is so sure that the mean of one population is larger (smaller) than the mean of the other and would never be smaller (larger) than the other, why would she needs to test for significance at all? This a rather philosophical question and it is beyond the scope of this article. Interested readers are invited to see part of the discussion in &lt;span class=&#34;citation&#34;&gt;Rowntree (&lt;a href=&#34;#ref-rowntree2000statistics&#34; role=&#34;doc-biblioref&#34;&gt;2000&lt;/a&gt;)&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;hypothesis-testing&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Hypothesis testing&lt;/h1&gt;
&lt;p&gt;In statistics, many statistical tests is in the form of &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt;. Hypothesis tests are used to determine whether a certain belief can be deemed as true (plausible) or not, based on the data at hand (i.e., the sample(s)). Most hypothesis tests boil down to the following 4 steps:&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;State the null and alternative hypothesis.&lt;/li&gt;
&lt;li&gt;Compute the test statistic, denoted t-stat. Formulas to compute the test statistic differ among the different versions of the Student’s t-test but they have the same structure. See scenarios 1 to 5 below to see the different formulas.&lt;/li&gt;
&lt;li&gt;Find the critical value given the theoretical statistical distribution of the test, the parameters of the distribution and the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;. For a Student’s t-test and its extended version, it is either the normal or the Student’s t distribution (&lt;em&gt;t&lt;/em&gt; denoting the Student distribution and &lt;em&gt;z&lt;/em&gt; denoting the normal distribution).&lt;/li&gt;
&lt;li&gt;Conclude by comparing the t-stat (found in step 2.) with the critical value (found in step. 3). If the t-stat lies in the rejection region (determined thanks to the critical value and the direction of the test), we reject the null hypothesis, otherwise we do not reject the null hypothesis. These two alternatives (reject or do not reject the null hypothesis) are the only two possible solutions, we never “accept” an hypothesis. It is also a good practice to always interpret the decision in the terms of the initial question.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;For the interested reader, see these 4 steps of hypothesis testing in more details in this &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;article&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;different-versions-of-the-students-t-test&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Different versions of the Student’s t-test&lt;/h1&gt;
&lt;p&gt;There are several versions of the Student’s t-test for two samples, depending on whether the samples are independent or paired and depending on whether the variances of the populations are (un)equal and/or (un)known:&lt;/p&gt;
&lt;div id=&#34;htmlwidget-1&#34; style=&#34;width:100%;height:480px;&#34; class=&#34;grViz html-widget&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-1&#34;&gt;{&#34;x&#34;:{&#34;diagram&#34;:&#34;digraph {\n\ngraph [rankdir = \&#34;LR\&#34;]\n\n\n\n  \&#34;1\&#34; [label = \&#34;Test on 2 means\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Test on 2 means\&#34;, fillcolor = \&#34;LightGray\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;2\&#34; [label = \&#34;2 independepent samples\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: 2 independepent samples\&#34;, fillcolor = \&#34;LightGray\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;3\&#34; [label = \&#34;2 variances are known (scenario 1)\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: 2 variances are known (scenario 1)\&#34;, fillcolor = \&#34;LightGray\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;4\&#34; [label = \&#34;2 variances are equal but unknown (scenario 2)\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: 2 variances are equal but unknown (scenario 2)\&#34;, fillcolor = \&#34;LightGray\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;5\&#34; [label = \&#34;2 variances are unequal and unknown (scenario 3)\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: 2 variances are unequal and unknown (scenario 3)\&#34;, fillcolor = \&#34;LightGray\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;6\&#34; [label = \&#34;2 paired samples\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: 2 paired samples\&#34;, fillcolor = \&#34;LightGray\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;7\&#34; [label = \&#34;Variance of the differences is known (scenario 4)\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Variance of the differences is known (scenario 4)\&#34;, fillcolor = \&#34;LightGray\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;8\&#34; [label = \&#34;Variance of the differences is unknown (scenario 5)\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Variance of the differences is unknown (scenario 5)\&#34;, fillcolor = \&#34;LightGray\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;1\&#34;-&gt;\&#34;2\&#34; \n  \&#34;1\&#34;-&gt;\&#34;6\&#34; \n  \&#34;2\&#34;-&gt;\&#34;3\&#34; \n  \&#34;2\&#34;-&gt;\&#34;4\&#34; \n  \&#34;2\&#34;-&gt;\&#34;5\&#34; \n  \&#34;6\&#34;-&gt;\&#34;7\&#34; \n  \&#34;6\&#34;-&gt;\&#34;8\&#34; \n}&#34;,&#34;config&#34;:{&#34;engine&#34;:&#34;dot&#34;,&#34;options&#34;:null}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;On the one hand, &lt;strong&gt;independent&lt;/strong&gt; samples means that the two samples are collected on &lt;strong&gt;different&lt;/strong&gt; experimental units or different individuals, for instance when we are working on women and men separately, or working on patients who have been randomly assigned to a control and a treatment group (and a patient belongs to only one group). On the other hand, we face &lt;strong&gt;paired&lt;/strong&gt; samples when measurements are collected on the &lt;strong&gt;same&lt;/strong&gt; experimental units, same individuals. This is often the case, for example in medical studies, when testing the efficiency of a treatment at two different times. The same patients are measured twice, before and after the treatment, and the dependency between the two samples must be taken into account in the computation of the test statistic by working on the &lt;strong&gt;differences&lt;/strong&gt; of measurements for each subject. Paired samples are usually the result of measurements at two different times, but not exclusively. Suppose we want to test the difference in vision between the left and right eyes of 50 athletes. Although the measurements are not made at two different time (before-after), it is clear that both eyes are dependent within each subject. Therefore, the Student’s t-test for paired samples should be used to account for the dependency between the two samples instead of the standard Student’s t-test for independent samples.&lt;/p&gt;
&lt;p&gt;Another criteria for choosing the appropriate version of the Student’s t-test is whether the variances of the populations (not the variances of the samples!) are known or unknown and equal or unequal. This criteria is rather straightforward, we either know the variances of the populations or we do not. The variances of the populations cannot be computed because if you can compute the variance of a population, it means you have the data for the whole population, then there is no need to do a hypothesis test anymore… So the variances of the populations are either given in the statement (use them in that case), or there is no information about these variances and in this case, it is assumed that the variances are unknown. In practice, the variances of the populations are most of the time unknown and the only thing to do in order to choose the appropriate version of the test is to check whether the variances are equal or not. However, we still illustrate how to do all versions of this test by hand and in R in the next sections following the 4 steps of hypothesis testing.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;how-to-compute-students-t-test-by-hand&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How to compute Student’s t-test by hand?&lt;/h1&gt;
&lt;p&gt;Note that the data are artificial and do not represent any real variable. Furthermore, remind that the assumptions may or may not be met. The point of the article is to detail how to compute the different versions of the test by hand and in R, so all assumptions are assumed to be met. Moreover, assume that the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 5\)&lt;/span&gt;% for all tests.&lt;/p&gt;
&lt;p&gt;If you are interested in applying these tests by hand without having to do the computations yourself, here is a &lt;a href=&#34;https://statsandr.com/blog/a-shiny-app-for-inferential-statistics-by-hand/&#34;&gt;Shiny app&lt;/a&gt; which does it for you. You just need to enter the data and choose the appropriate version of the test thanks to the sidebar menu. There is also a graphical representation that helps you to visualize the test statistic and the rejection region. I hope you will find it useful!&lt;/p&gt;
&lt;div id=&#34;scenario-1-independent-samples-with-2-known-variances&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 1: Independent samples with 2 known variances&lt;/h2&gt;
&lt;p&gt;For the first scenario, suppose the data below. Moreover, suppose that the two samples are independent, that the variances &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2 = 1\)&lt;/span&gt; in both populations and that we would like to test whether the two population means are different.&lt;/p&gt;
&lt;table style=&#34;width:24%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;11%&#34; /&gt;
&lt;col width=&#34;12%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt;value&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;sample&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;-0.8&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;-0.3&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.8&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;-0.9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;-0.1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.4&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;So we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;5 observations in each sample: &lt;span class=&#34;math inline&#34;&gt;\(n_1 = n_2 = 5\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;mean of sample 1: &lt;span class=&#34;math inline&#34;&gt;\(\bar{x}_1 = 0.02\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;mean of sample 2: &lt;span class=&#34;math inline&#34;&gt;\(\bar{x}_2 = 0.06\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;variances of both populations: &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2_1 = \sigma^2_2 = 1\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Following the 4 steps of hypothesis testing we have:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu_1 = \mu_2\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu_1 - \mu_2 \ne 0\)&lt;/span&gt;. (&lt;span class=&#34;math inline&#34;&gt;\(\ne\)&lt;/span&gt; because we want to test whether the two means are different, we do not impose a direction in the test.)&lt;/li&gt;
&lt;li&gt;Test statistic: &lt;span class=&#34;math display&#34;&gt;\[z_{obs} = \frac{(\bar{x}_1 - \bar{x}_2) - (\mu_1 - \mu_2)}{\sqrt{\frac{\sigma^2_1}{n_1} + \frac{\sigma^2_2}{n_2}}}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[= \frac{0.02-0.06-0}{0.632} = -0.063\]&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Critical value: &lt;span class=&#34;math inline&#34;&gt;\(\pm z_{\alpha / 2} = \pm z_{0.025} = \pm 1.96\)&lt;/span&gt; (see a guide on &lt;a href=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/&#34;&gt;how to read statistical tables&lt;/a&gt; if you struggle to find the critical value)&lt;/li&gt;
&lt;li&gt;Conclusion: The rejection regions are thus from &lt;span class=&#34;math inline&#34;&gt;\(-\infty\)&lt;/span&gt; to -1.96 and from 1.96 to &lt;span class=&#34;math inline&#34;&gt;\(+\infty\)&lt;/span&gt;. The test statistic is outside the rejection regions so we do not reject the null hypothesis &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;. In terms of the initial question: At the 5% significance level, we do not reject the hypothesis that the two population means are the same, or there is no sufficient evidence in the data to conclude that the two populations considered are different.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div id=&#34;scenario-2-independent-samples-with-2-equal-but-unknown-variances&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 2: Independent samples with 2 equal but unknown variances&lt;/h2&gt;
&lt;p&gt;For the second scenario, suppose the data below. Moreover, suppose that the two samples are independent, that the variances in both populations are unknown but equal (&lt;span class=&#34;math inline&#34;&gt;\(\sigma^2_1 = \sigma^2_1\)&lt;/span&gt;) and that we would like to test whether the mean of population 1 is larger than the mean of population 2.&lt;/p&gt;
&lt;table style=&#34;width:24%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;11%&#34; /&gt;
&lt;col width=&#34;12%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt;value&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;sample&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1.78&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1.5&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.6&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.8&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1.9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.8&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;-0.7&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;-0.1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.4&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;So we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;6 observations in sample 1: &lt;span class=&#34;math inline&#34;&gt;\(n_1 = 6\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;5 observations in sample 2: &lt;span class=&#34;math inline&#34;&gt;\(n_2 = 5\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;mean of sample 1: &lt;span class=&#34;math inline&#34;&gt;\(\bar{x}_1 = 1.247\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;mean of sample 2: &lt;span class=&#34;math inline&#34;&gt;\(\bar{x}_2 = 0.1\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;variance of sample 1: &lt;span class=&#34;math inline&#34;&gt;\(s^2_1 = 0.303\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;variance of sample 2: &lt;span class=&#34;math inline&#34;&gt;\(s^2_1 = 0.315\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Following the 4 steps of hypothesis testing we have:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu_1 = \mu_2\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu_1 - \mu_2 &amp;gt; 0\)&lt;/span&gt;. (&amp;gt; because we want to test if the mean of the first population is larger than the mean of the second population.)&lt;/li&gt;
&lt;li&gt;Test statistic: &lt;span class=&#34;math display&#34;&gt;\[t_{obs} = \frac{(\bar{x}_1 - \bar{x}_2) - (\mu_1 - \mu_2)}{s_p\sqrt{\frac{1}{n_1} + \frac{1}{n_2}}}\]&lt;/span&gt; where &lt;span class=&#34;math display&#34;&gt;\[s_p = \sqrt{\frac{(n_1-1)s^2_1+ (n_2 - 1)s^2_2}{n_1 + n_2 - 2}} = 0.555\]&lt;/span&gt; so &lt;span class=&#34;math display&#34;&gt;\[t_{obs} = \frac{1.247-0.1-0}{0.555 * 0.606} = 3.411\]&lt;/span&gt;
(Note that as it is assumed the variances of the two populations are equal, a pooled (common) variance, denoted &lt;span class=&#34;math inline&#34;&gt;\(s_p\)&lt;/span&gt;, is computed.)&lt;/li&gt;
&lt;li&gt;Critical value: &lt;span class=&#34;math inline&#34;&gt;\(t_{\alpha, n_1 + n_2 - 2} = t_{0.05, 9} = 1.833\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Conclusion: The rejection region is thus from 1.833 to &lt;span class=&#34;math inline&#34;&gt;\(+\infty\)&lt;/span&gt; (there is only one rejection region because it is a one-sided test). The test statistic lies within the rejection region so we reject the null hypothesis &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;. In terms of the initial question: At the 5% significance level, we conclude that the mean of population 1 is larger than the mean of population 2.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div id=&#34;scenario-3-independent-samples-with-2-unequal-and-unknown-variances&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 3: Independent samples with 2 unequal and unknown variances&lt;/h2&gt;
&lt;p&gt;For the third scenario, suppose the data below. Moreover, suppose that the two samples are independent, that the variances in both populations are unknown and unequal (&lt;span class=&#34;math inline&#34;&gt;\(\sigma^2_1 \ne \sigma^2_1\)&lt;/span&gt;) and that we would like to test whether the mean of population 1 is smaller than the mean of population 2.&lt;/p&gt;
&lt;table style=&#34;width:24%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;11%&#34; /&gt;
&lt;col width=&#34;12%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt;value&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;sample&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.8&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.7&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.4&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1.78&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1.5&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.6&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.8&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1.9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;So we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;5 observations in sample 1: &lt;span class=&#34;math inline&#34;&gt;\(n_1 = 5\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;6 observations in sample 2: &lt;span class=&#34;math inline&#34;&gt;\(n_2 = 6\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;mean of sample 1: &lt;span class=&#34;math inline&#34;&gt;\(\bar{x}_1 = 0.42\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;mean of sample 2: &lt;span class=&#34;math inline&#34;&gt;\(\bar{x}_2 = 1.247\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;variance of sample 1: &lt;span class=&#34;math inline&#34;&gt;\(s^2_1 = 0.107\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;variance of sample 2: &lt;span class=&#34;math inline&#34;&gt;\(s^2_1 = 0.303\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Following the 4 steps of hypothesis testing we have:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu_1 = \mu_2\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu_1 - \mu_2 &amp;lt; 0\)&lt;/span&gt;. (&amp;lt; because we want to test if the mean of the first population is smaller than the mean of the second population.)&lt;/li&gt;
&lt;li&gt;Test statistic: &lt;span class=&#34;math display&#34;&gt;\[t_{obs} = \frac{(\bar{x}_1 - \bar{x}_2) - (\mu_1 - \mu_2)}{\sqrt{\frac{s^2_1}{n_1} + \frac{s^2_2}{n_2}}}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[= \frac{0.42-1.247-0}{0.268} = -3.084\]&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Critical value: &lt;span class=&#34;math inline&#34;&gt;\(-t_{\alpha, \upsilon}\)&lt;/span&gt; where &lt;span class=&#34;math display&#34;&gt;\[\upsilon = \frac{\bigg(\frac{s^2_1}{n_1} + \frac{s^2_2}{n_2} \bigg)^2}{\frac{\bigg(\frac{s^2_1}{n_1}\bigg)^2}{n_1 - 1} + \frac{\bigg(\frac{s^2_2}{n_2}\bigg)^2}{n_2 - 1}} = 8.28\]&lt;/span&gt; so &lt;span class=&#34;math display&#34;&gt;\[-t_{0.05, 8.28} = -1.851\]&lt;/span&gt;
&lt;em&gt;Note:&lt;/em&gt; The degrees of freedom 8.28 does not exist in the standard Student distribution table, so simply take 8, or compute it in R with &lt;code&gt;qt(p = 0.05, df = 8.28)&lt;/code&gt;. For simplicity, this number of degrees of freedom is sometimes approximated as &lt;span class=&#34;math inline&#34;&gt;\(df = min(n_1 - 1, n_2 - 1)\)&lt;/span&gt;, so in this case it would be &lt;span class=&#34;math inline&#34;&gt;\(df = 4\)&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;Conclusion: The rejection region is thus from &lt;span class=&#34;math inline&#34;&gt;\(-\infty\)&lt;/span&gt; to -1.851. The test statistic lies within the rejection region so we reject the null hypothesis &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;. In terms of the initial question: At the 5% significance level, we conclude that the mean of population 1 is smaller than the mean of population 2.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div id=&#34;scenario-4-paired-samples-where-the-variance-of-the-differences-is-known&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 4: Paired samples where the variance of the differences is known&lt;/h2&gt;
&lt;p&gt;Student’s t-test with paired samples are a bit different than with independent samples, they are actually more similar to &lt;a href=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r-test-on-one-mean/&#34;&gt;one sample Student’s t-test&lt;/a&gt;. Here is how it works. We actually compute the difference between the two samples for each pair of observations, and then we work on these differences as if we were doing a one sample Student’s t-test by computing the test statistic on these differences.&lt;/p&gt;
&lt;p&gt;In case it is not clear, here is the fourth scenario as an illustration. Suppose the data below. Moreover, suppose that the two samples are dependent (matched), that the variance of the differences in the population is known and equal to 1 (&lt;span class=&#34;math inline&#34;&gt;\(\sigma^2_D = 1\)&lt;/span&gt;) and that we would like to test whether the mean difference between the two populations is different than 0.&lt;/p&gt;
&lt;table style=&#34;width:25%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;12%&#34; /&gt;
&lt;col width=&#34;12%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt;before&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;after&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.8&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;-0.8&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;-0.9&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;-0.1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;-0.3&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.4&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.1&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The first thing to do is to compute the differences for all pairs of observations:&lt;/p&gt;
&lt;table style=&#34;width:42%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;12%&#34; /&gt;
&lt;col width=&#34;11%&#34; /&gt;
&lt;col width=&#34;18%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt;before&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;after&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;difference&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.8&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;-0.1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;-0.8&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;-0.9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;-0.1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;-0.1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;-0.2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;-0.3&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.4&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.7&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0.1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;-0.1&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;So we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;number of pairs: &lt;span class=&#34;math inline&#34;&gt;\(n = 5\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;mean of the difference: &lt;span class=&#34;math inline&#34;&gt;\(\bar{D} = 0.04\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;variance of the difference in the population: &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2_D = 1\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;standard deviation of the difference in the population: &lt;span class=&#34;math inline&#34;&gt;\(\sigma_D = 1\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Following the 4 steps of hypothesis testing we have:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu_D = 0\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu_D \ne 0\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Test statistic: &lt;span class=&#34;math display&#34;&gt;\[z_{obs} = \frac{\bar{D} - \mu_0}{\frac{\sigma_D}{\sqrt{n}}} = \frac{0.04-0}{0.447} = 0.089\]&lt;/span&gt;
(This formula is exactly the same than for one sample Student’s t-test with a known variance, except that we work on the mean of the differences.)&lt;/li&gt;
&lt;li&gt;Critical value: &lt;span class=&#34;math inline&#34;&gt;\(\pm z_{\alpha/2} = \pm z_{0.025} = \pm 1.96\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Conclusion: The rejection regions are thus from &lt;span class=&#34;math inline&#34;&gt;\(-\infty\)&lt;/span&gt; to -1.96 and from 1.96 to &lt;span class=&#34;math inline&#34;&gt;\(+\infty\)&lt;/span&gt;. The test statistic is outside the rejection regions so we do not reject the null hypothesis &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;. In terms of the initial question: At the 5% significance level, we do not reject the hypothesis that the mean difference between the two populations is equal to 0.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div id=&#34;scenario-5-paired-samples-where-the-variance-of-the-differences-is-unknown&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 5: Paired samples where the variance of the differences is unknown&lt;/h2&gt;
&lt;p&gt;For the fifth and final scenario, suppose the data below. Moreover, suppose that the two samples are dependent (matched), that the variance of the differences in the population is unknown and that we would like to test whether a treatment is effective in increasing running capabilities (the higher the value, the better in terms of running capabilities).&lt;/p&gt;
&lt;table style=&#34;width:25%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;12%&#34; /&gt;
&lt;col width=&#34;12%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt;before&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;after&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;16&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;8&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;11&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;15&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;3&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;12&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;9&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The first thing to do is to compute the differences for all pairs of observations:&lt;/p&gt;
&lt;table style=&#34;width:42%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;12%&#34; /&gt;
&lt;col width=&#34;11%&#34; /&gt;
&lt;col width=&#34;18%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt;before&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;after&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;difference&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;16&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;7&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;8&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;11&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;15&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;14&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;3&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;12&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;9&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;7&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;So we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;number of pairs: &lt;span class=&#34;math inline&#34;&gt;\(n = 5\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;mean of the difference: &lt;span class=&#34;math inline&#34;&gt;\(\bar{D} = 8\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;variance of the difference in the sample: &lt;span class=&#34;math inline&#34;&gt;\(s^2_D = 16\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;standard deviation of the difference in the sample: &lt;span class=&#34;math inline&#34;&gt;\(s_D = 4\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Following the 4 steps of hypothesis testing we have:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu_D = 0\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu_D &amp;gt; 0\)&lt;/span&gt; (&amp;gt; because we would like to test whether the treatment is effective, so whether the treatment has a positive impact on the running capabilities.)&lt;/li&gt;
&lt;li&gt;Test statistic: &lt;span class=&#34;math display&#34;&gt;\[t_{obs} = \frac{\bar{D} - \mu_0}{\frac{s_D}{\sqrt{n}}} = \frac{8-0}{1.789} = 4.472\]&lt;/span&gt;
(This formula is exactly the same than for one sample Student’s t-test with an unknown variance, except that we work on the mean of the differences.)&lt;/li&gt;
&lt;li&gt;Critical value: &lt;span class=&#34;math inline&#34;&gt;\(t_{\alpha, n-1} = t_{0.05, 4} = 2.132\)&lt;/span&gt; (&lt;em&gt;n&lt;/em&gt; is the number of pairs, not the number of observations!)&lt;/li&gt;
&lt;li&gt;Conclusion: The rejection regions are thus from 2.132 to &lt;span class=&#34;math inline&#34;&gt;\(+\infty\)&lt;/span&gt;. The test statistic lies within the rejection region so we reject the null hypothesis &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;. In terms of the initial question: At the 5% significance level, we conclude that the treatment has a positive impact on the running capabilities (because the mean of the differences is greater than 0)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This concludes how to perform the different versions of the Student’s t-test for two samples by hand. In the next sections, we detail how to perform the exact same tests in R.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;how-to-compute-students-t-test-in-r&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How to compute Student’s t-test in R?&lt;/h1&gt;
&lt;p&gt;A good practice before doing t-tests in R is to visualize the data by group thanks to a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#boxplot&#34;&gt;boxplot&lt;/a&gt; (or a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#density-plot&#34;&gt;density plot&lt;/a&gt;, or eventually both). A boxplot with the two boxes overlapping each other gives a first indication that the two samples are similar, and thus, that the null hypothesis of equal means may not be rejected. On the contrary, if the two boxes are not overlapping, it indicates that the two samples are not similar, and thus, that the populations may be different in terms of the considered variable. However, even if boxplots or density plots are great in showing a comparison between the two groups, only a sound statistical test will confirm our first impression.&lt;/p&gt;
&lt;p&gt;After a visualization of the data by group, we replicate in R the results found by hand. We will see that for some versions of the t-test, there is no default function built in R (at least to my knowledge, do not hesitate to let me know in the comments if I’m mistaken). In these cases, a function is written to replicate the results by hand.&lt;/p&gt;
&lt;p&gt;Note that we use the same data, the same assumptions and the same question for all 5 scenarios to facilitate the comparison between the tests performed by hand and in R.&lt;/p&gt;
&lt;div id=&#34;scenario-1-independent-samples-with-2-known-variances-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 1: Independent samples with 2 known variances&lt;/h2&gt;
&lt;p&gt;For the first scenario, suppose the data below. Moreover, suppose that the two samples are independent, that the variances &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2 = 1\)&lt;/span&gt; in both populations and that we would like to test whether the two population means are different.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat1 &amp;lt;- data.frame(
  sample1 = c(0.9, -0.8, 0.1, -0.3, 0.2),
  sample2 = c(0.8, -0.9, -0.1, 0.4, 0.1)
)
dat1&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   sample1 sample2
## 1     0.9     0.8
## 2    -0.8    -0.9
## 3     0.1    -0.1
## 4    -0.3     0.4
## 5     0.2     0.1&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat_ggplot &amp;lt;- data.frame(
  value = c(0.9, -0.8, 0.1, -0.3, 0.2, 0.8, -0.9, -0.1, 0.4, 0.1),
  sample = c(rep(&amp;quot;1&amp;quot;, 5), rep(&amp;quot;2&amp;quot;, 5))
)

library(ggplot2)

ggplot(dat_ggplot) +
  aes(x = sample, y = value) +
  geom_boxplot() +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios_files/figure-html/unnamed-chunk-10-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Note that you can use the &lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#esquisse&#34;&gt;&lt;code&gt;{esquisse}&lt;/code&gt; RStudio addin&lt;/a&gt; if you want to draw a boxplot with the &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;package &lt;code&gt;{ggplot2}&lt;/code&gt;&lt;/a&gt; without writing the code yourself. If you prefer the default graphics, use the &lt;code&gt;boxplot()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;boxplot(value ~ sample,
  data = dat_ggplot
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios_files/figure-html/unnamed-chunk-11-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The two boxes seem to overlap which illustrate that the two samples are quite similar, so we tend to believe that we will not be able to reject the null hypothesis that the two population means are similar. However, only a formal statistical test will confirm this belief.&lt;/p&gt;
&lt;p&gt;Below a function to perform a t-test with known variances, with arguments accepting:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the two samples (&lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt;),&lt;/li&gt;
&lt;li&gt;the two variances of the populations (&lt;code&gt;V1&lt;/code&gt; and &lt;code&gt;V2&lt;/code&gt;),&lt;/li&gt;
&lt;li&gt;the difference in means under the null hypothesis (&lt;code&gt;m0&lt;/code&gt;, default is &lt;code&gt;0&lt;/code&gt;),&lt;/li&gt;
&lt;li&gt;the significance level (&lt;code&gt;alpha&lt;/code&gt;, default is &lt;code&gt;0.05&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;and the alternative (&lt;code&gt;alternative&lt;/code&gt;, one of &lt;code&gt;&#34;two.sided&#34;&lt;/code&gt; (default), &lt;code&gt;&#34;less&#34;&lt;/code&gt; or &lt;code&gt;&#34;greater&#34;&lt;/code&gt;):&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;t.test_knownvar &amp;lt;- function(x, y, V1, V2, m0 = 0, alpha = 0.05, alternative = &amp;quot;two.sided&amp;quot;) {
  M1 &amp;lt;- mean(x)
  M2 &amp;lt;- mean(y)
  n1 &amp;lt;- length(x)
  n2 &amp;lt;- length(y)
  sigma1 &amp;lt;- sqrt(V1)
  sigma2 &amp;lt;- sqrt(V2)
  S &amp;lt;- sqrt((V1 / n1) + (V2 / n2))
  statistic &amp;lt;- (M1 - M2 - m0) / S
  p &amp;lt;- if (alternative == &amp;quot;two.sided&amp;quot;) {
    2 * pnorm(abs(statistic), lower.tail = FALSE)
  } else if (alternative == &amp;quot;less&amp;quot;) {
    pnorm(statistic, lower.tail = TRUE)
  } else {
    pnorm(statistic, lower.tail = FALSE)
  }
  LCL &amp;lt;- (M1 - M2 - S * qnorm(1 - alpha / 2))
  UCL &amp;lt;- (M1 - M2 + S * qnorm(1 - alpha / 2))
  value &amp;lt;- list(mean1 = M1, mean2 = M2, m0 = m0, sigma1 = sigma1, sigma2 = sigma2, S = S, statistic = statistic, p.value = p, LCL = LCL, UCL = UCL, alternative = alternative)
  # print(sprintf(&amp;quot;P-value = %g&amp;quot;,p))
  # print(sprintf(&amp;quot;Lower %.2f%% Confidence Limit = %g&amp;quot;,
  #               alpha, LCL))
  # print(sprintf(&amp;quot;Upper %.2f%% Confidence Limit = %g&amp;quot;,
  #               alpha, UCL))
  return(value)
}

test &amp;lt;- t.test_knownvar(dat1$sample1, dat1$sample2,
  V1 = 1, V2 = 1
)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $mean1
## [1] 0.02
## 
## $mean2
## [1] 0.06
## 
## $m0
## [1] 0
## 
## $sigma1
## [1] 1
## 
## $sigma2
## [1] 1
## 
## $S
## [1] 0.6324555
## 
## $statistic
## [1] -0.06324555
## 
## $p.value
## [1] 0.949571
## 
## $LCL
## [1] -1.27959
## 
## $UCL
## [1] 1.19959
## 
## $alternative
## [1] &amp;quot;two.sided&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output above recaps all the information needed to perform the test: the test statistic, the &lt;em&gt;p&lt;/em&gt;-value, the alternative used, the two sample means and the two variances of the populations (compare these results found in R with the results found by hand).&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value can be extracted as usual:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$p.value&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.949571&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.95 so at the 5% significance level we do not reject the null hypothesis of equal means. There is no sufficient evidence in the data to reject the hypothesis that the two means in the populations are similar. This result confirms what we found by hand.&lt;/p&gt;
&lt;p&gt;Note that a similar function exists in the &lt;code&gt;{BSDA}&lt;/code&gt; package:&lt;a href=&#34;#fn4&#34; class=&#34;footnote-ref&#34; id=&#34;fnref4&#34;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(BSDA)

z.test(dat1$sample1,
  dat1$sample2,
  alternative = &amp;quot;two.sided&amp;quot;,
  mu = 0,
  sigma.x = 1,
  sigma.y = 1,
  conf.level = 0.95
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Two-sample z-Test
## 
## data:  dat1$sample1 and dat1$sample2
## z = -0.063246, p-value = 0.9496
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  -1.27959  1.19959
## sample estimates:
## mean of x mean of y 
##      0.02      0.06&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;a-note-on-p-value-and-significance-level-alpha&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;A note on &lt;em&gt;p&lt;/em&gt;-value and significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;For those unfamiliar with the concept of &lt;em&gt;p&lt;/em&gt;-value, the &lt;em&gt;p&lt;/em&gt;-value is a &lt;a href=&#34;https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/&#34;&gt;probability&lt;/a&gt; and as any probability it goes from 0 to 1. The &lt;strong&gt;&lt;em&gt;p&lt;/em&gt;-value is the probability of having observations at least as extreme as the one we measured (via the samples) if the null hypothesis were true&lt;/strong&gt;. In other words, it is the probability of having a test statistic at least as extreme as the one we computed, given that the null hypothesis is true. In some sense, it gives you an indication on &lt;strong&gt;how likely your null hypothesis is&lt;/strong&gt;. It is also defined as the smallest level of significance for which the data indicate rejection of the null hypothesis.&lt;/p&gt;
&lt;p&gt;If the observations are not so extreme—not unlikely to occur if the null hypothesis were true—we do not reject this null hypothesis because it is deemed plausible to be true. And if the observations are considered too extreme—too unlikely to happen under the null hypothesis—we reject the null hypothesis because it is deemed too implausible to be true. Note that it does not mean that we are 100% sure that it is too unlikely, it happens sometimes that the null hypothesis is rejected although it is true (see the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; later on).&lt;/p&gt;
&lt;p&gt;In our example above, the observations are not really extreme and the difference between the two means is not extreme, so the test statistic is not extreme (since the test statistic is partially based on the difference of the means of the two samples). Having a test statistic which is not extreme is not unlikely and that is the reason why the &lt;em&gt;p&lt;/em&gt;-value is quite high. The &lt;em&gt;p&lt;/em&gt;-value of 0.95 actually tells us that the probability of having two samples with a difference in means of -0.04 (= 0.02 - 0.06), given that the difference in means in the populations is 0 (the null hypothesis), equals 95%. A probability of 95% is definitely considered as plausible, so we do not reject the null hypothesis of equal means in the populations.&lt;/p&gt;
&lt;p&gt;One may then wonder, “What is too extreme for a test statistic?” Most of the time, we consider that a test statistic is too extreme to happen just by chance when the probability of having such an extreme test statistic given that the null hypothesis is true is below 5%. The threshold of 5% (&lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;) that you very often see in statistic courses or textbooks is the threshold used in many fields. With a &lt;em&gt;p&lt;/em&gt;-value under that threshold of 5%, we consider that the observations (and thus the test statistic) is &lt;strong&gt;too unlikely&lt;/strong&gt; to happen just by chance if the null hypothesis were true, so the null hypothesis is rejected. With a &lt;em&gt;p&lt;/em&gt;-value above that threshold of 5%, we consider that it is not really implausible to face the observations we have if the null hypothesis were true, and we therefore do not reject the null hypothesis.&lt;/p&gt;
&lt;p&gt;Note that I wrote “we do not reject the null hypothesis”, and not “we accept the null hypothesis”. This is because it may be the case that the null hypothesis is in fact false, but we failed to prove it with the samples. Suppose the analogy of a suspect accused of murder and we do not know the truth. On the one hand, if we have collected enough evidence that the suspect committed the murder, he is considered guilty: we reject the null hypothesis that he is innocent. On the other hand, if we have &lt;em&gt;not&lt;/em&gt; collected enough evidence against the suspect, he is presumed to be innocent although he may in fact have committed the crime: we failed to reject the null hypothesis of him being innocent. We are never sure that he did not commit the crime even if he is released, we just did not find sufficient evidence against the null hypothesis of the suspect being innocent. This is the reason why we do not reject the null hypothesis instead of accepting it, and why you will often read things like “there is no sufficient evidence in the data to reject the null hypothesis” or “based on the samples we fail to reject the null hypothesis”.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;&lt;/strong&gt;, derived from the threshold of 5% mentioned earlier, &lt;strong&gt;is the probability of rejecting the null hypothesis when it is in fact true&lt;/strong&gt;. In this sense, it is an error (of 5%) that we accept to deal with, in order to be able to draw conclusions. If we would accept no error (an error of 0%), we would not be able to draw any conclusion about the population(s) since we only have access to a limited portion of the population(s) via the sample(s). As a consequence, we will never be 100% sure when interpreting the result of a hypothesis test unless we have access to the data for the entire population, but then there is no reason to do a hypothesis test anymore since we can simply compare the two populations. We usually allow this error (called Type I error) to be 5%, but in order to be a bit more certain when concluding that we reject the null hypothesis, the alpha level can also be set to 1% (or even to 0.1% in some rare cases).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;To sum up&lt;/strong&gt; what you need to remember about &lt;em&gt;p&lt;/em&gt;-value and significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If the &lt;em&gt;p&lt;/em&gt;-value is smaller than the predetermined significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; (usually 5%) so if &lt;em&gt;p&lt;/em&gt;-value &amp;lt; 0.05 &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow H_0\)&lt;/span&gt; is unlikely &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow\)&lt;/span&gt; we reject the null hypothesis&lt;/li&gt;
&lt;li&gt;If the &lt;em&gt;p&lt;/em&gt;-value is greater than or equal to the predetermined significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; (usually 5%) so if &lt;em&gt;p&lt;/em&gt;-value &lt;span class=&#34;math inline&#34;&gt;\(\ge\)&lt;/span&gt; 0.05 &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow H_0\)&lt;/span&gt; is likely &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow\)&lt;/span&gt; we do &lt;strong&gt;not reject&lt;/strong&gt; the null hypothesis&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This applies to all statistical tests without exception. Of course, the null and alternative hypotheses change depending on the test.&lt;/p&gt;
&lt;p&gt;A rule of thumb is that, for most hypothesis tests, the alternative hypothesis is what you want to test and the null hypothesis is the status quo. Take this with extreme caution (!) because, even if it works for all versions of the Student’s t-test it does not apply to ALL statistical tests. For example, when testing for normality, you usually want to test whether your distribution follows a normal distribution. Following this piece of advice, you would write the alternative hypothesis &lt;span class=&#34;math inline&#34;&gt;\(H_1:\)&lt;/span&gt; the distribution follows a normal distribution. Nonetheless, for &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#normality-test&#34;&gt;normality tests&lt;/a&gt; such as the Shapiro-Wilk or Kolmogorov-Smirnov test, it is the opposite; the alternative hypothesis is &lt;span class=&#34;math inline&#34;&gt;\(H_1:\)&lt;/span&gt; the distribution does not follow a normal distribution. So for every test, make sure to use the correct hypotheses, otherwise the conclusion and interpretation of your test will be wrong.&lt;/p&gt;
&lt;p&gt;Last but not least, note that statistical significance is &lt;strong&gt;not&lt;/strong&gt; equal to scientific significance. To this end, a result may be &lt;em&gt;statistically&lt;/em&gt; significant (a &lt;em&gt;p&lt;/em&gt;-value &amp;lt; &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;), but of little or no interest from a &lt;em&gt;scientific&lt;/em&gt; point of view (because the effect is so small that it is negligible and/or useless for instance).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;scenario-2-independent-samples-with-2-equal-but-unknown-variances-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 2: Independent samples with 2 equal but unknown variances&lt;/h2&gt;
&lt;p&gt;For the second scenario, suppose the data below. Moreover, suppose that the two samples are independent, that the variances in both populations are unknown but equal (&lt;span class=&#34;math inline&#34;&gt;\(\sigma^2_1 = \sigma^2_1\)&lt;/span&gt;) and that we would like to test whether the mean of population 1 is larger than the mean of population 2.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat2 &amp;lt;- data.frame(
  sample1 = c(1.78, 1.5, 0.9, 0.6, 0.8, 1.9),
  sample2 = c(0.8, -0.7, -0.1, 0.4, 0.1, NA)
)
dat2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   sample1 sample2
## 1    1.78     0.8
## 2    1.50    -0.7
## 3    0.90    -0.1
## 4    0.60     0.4
## 5    0.80     0.1
## 6    1.90      NA&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat_ggplot &amp;lt;- data.frame(
  value = c(1.78, 1.5, 0.9, 0.6, 0.8, 1.9, 0.8, -0.7, -0.1, 0.4, 0.1),
  sample = c(rep(&amp;quot;1&amp;quot;, 6), rep(&amp;quot;2&amp;quot;, 5))
)

ggplot(dat_ggplot) +
  aes(x = sample, y = value) +
  geom_boxplot() +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios_files/figure-html/unnamed-chunk-16-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Unlike the previous scenario, the two boxes do not overlap which illustrates that the two samples are different from each other. From this boxplot, we can expect the test to reject the null hypothesis of equal means in the populations. Nonetheless, only a formal statistical test will confirm this expectation.&lt;/p&gt;
&lt;p&gt;There is a function in R, and it is simply the &lt;code&gt;t.test()&lt;/code&gt; function. This version of the test is actually the “standard” Student’s t-test for two samples. Note that it is assumed that the variances of the two populations are equal so we need to specify it in the function with the argument &lt;code&gt;var.equal = TRUE&lt;/code&gt; (the default is &lt;code&gt;FALSE&lt;/code&gt;) and the alternative hypothesis is &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu_1 - \mu_2 &amp;gt; 0\)&lt;/span&gt; so we need to add the argument &lt;code&gt;alternative = &#34;greater&#34;&lt;/code&gt; as well:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- t.test(dat2$sample1, dat2$sample2,
  var.equal = TRUE, alternative = &amp;quot;greater&amp;quot;
)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Two Sample t-test
## 
## data:  dat2$sample1 and dat2$sample2
## t = 3.4113, df = 9, p-value = 0.003867
## alternative hypothesis: true difference in means is greater than 0
## 95 percent confidence interval:
##  0.5304908       Inf
## sample estimates:
## mean of x mean of y 
##  1.246667  0.100000&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output above recaps all the information needed to perform the test: the name of the test, the test statistic, the degrees of freedom, the &lt;em&gt;p&lt;/em&gt;-value, the alternative used and the two sample means (compare these results found in R with the results found by hand).&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value can be extracted as usual:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$p.value&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.003866756&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.004 so at the 5% significance level we reject the null hypothesis of equal means. This result confirms what we found by hand.&lt;/p&gt;
&lt;p&gt;Unlike the first scenario, the &lt;em&gt;p&lt;/em&gt;-value in this scenario is below 5% so we reject the null hypothesis. At the 5% significance level, we can conclude that the mean of population 1 is larger than the mean of population 2.&lt;/p&gt;
&lt;p&gt;A nice and easy way to report results of a Student’s t-test in R is with the &lt;code&gt;report()&lt;/code&gt; function from the &lt;code&gt;{report}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# install.packages(&amp;quot;remotes&amp;quot;)
# remotes::install_github(&amp;quot;easystats/report&amp;quot;) # You only need to do that once
library(&amp;quot;report&amp;quot;) # Load the package every time you start R

report(test)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Effect sizes were labelled following Cohen&amp;#39;s (1988) recommendations.
## 
## The Two Sample t-test testing the difference between dat2$sample1 and
## dat2$sample2 (mean of x = 1.25, mean of y = 0.10) suggests that the effect is
## positive, statistically significant, and large (difference = 1.15, 95% CI
## [0.53, Inf], t(9) = 3.41, p = 0.004; Cohen&amp;#39;s d = 2.07, 95% CI [0.75, Inf])&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, the function interprets the test (together with the &lt;em&gt;p&lt;/em&gt;-value) for you.&lt;/p&gt;
&lt;p&gt;Note that the &lt;code&gt;report()&lt;/code&gt; function can be used for other analyses. See more &lt;a href=&#34;https://statsandr.com/blog/tips-and-tricks-in-rstudio-and-r-markdown/&#34;&gt;tips and tricks in R&lt;/a&gt; if you find this one useful.&lt;/p&gt;
&lt;p&gt;If your data is formatted in the long format (which is even better), simply use the tilde (&lt;code&gt;~&lt;/code&gt;). For instance, imagine the exact same data presented like this:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat2bis &amp;lt;- data.frame(
  value = c(1.78, 1.5, 0.9, 0.6, 0.8, 1.9, 0.8, -0.7, -0.1, 0.4, 0.1),
  sample = c(rep(&amp;quot;1&amp;quot;, 6), rep(&amp;quot;2&amp;quot;, 5))
)
dat2bis&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    value sample
## 1   1.78      1
## 2   1.50      1
## 3   0.90      1
## 4   0.60      1
## 5   0.80      1
## 6   1.90      1
## 7   0.80      2
## 8  -0.70      2
## 9  -0.10      2
## 10  0.40      2
## 11  0.10      2&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here is how to perform the Student’s t-test in R with data in the long format:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- t.test(value ~ sample,
  data = dat2bis,
  var.equal = TRUE,
  alternative = &amp;quot;greater&amp;quot;
)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Two Sample t-test
## 
## data:  value by sample
## t = 3.4113, df = 9, p-value = 0.003867
## alternative hypothesis: true difference in means between group 1 and group 2 is greater than 0
## 95 percent confidence interval:
##  0.5304908       Inf
## sample estimates:
## mean in group 1 mean in group 2 
##        1.246667        0.100000&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$p.value&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.003866756&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The results are exactly the same.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;scenario-3-independent-samples-with-2-unequal-and-unknown-variances-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 3: Independent samples with 2 unequal and unknown variances&lt;/h2&gt;
&lt;p&gt;For the third scenario, suppose the data below. Moreover, suppose that the two samples are independent, that the variances in both populations are unknown and unequal (&lt;span class=&#34;math inline&#34;&gt;\(\sigma^2_1 \ne \sigma^2_1\)&lt;/span&gt;) and that we would like to test whether the mean of population 1 is smaller than the mean of population 2.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat3 &amp;lt;- data.frame(
  value = c(0.8, 0.7, 0.1, 0.4, 0.1, 1.78, 1.5, 0.9, 0.6, 0.8, 1.9),
  sample = c(rep(&amp;quot;1&amp;quot;, 5), rep(&amp;quot;2&amp;quot;, 6))
)
dat3&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    value sample
## 1   0.80      1
## 2   0.70      1
## 3   0.10      1
## 4   0.40      1
## 5   0.10      1
## 6   1.78      2
## 7   1.50      2
## 8   0.90      2
## 9   0.60      2
## 10  0.80      2
## 11  1.90      2&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat3) +
  aes(x = sample, y = value) +
  geom_boxplot() +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios_files/figure-html/unnamed-chunk-23-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;There is a function in R for this version of the test as well, and it is simply the &lt;code&gt;t.test()&lt;/code&gt; function with the &lt;code&gt;var.equal = FALSE&lt;/code&gt; argument. &lt;code&gt;FALSE&lt;/code&gt; is the default option for the &lt;code&gt;var.equal&lt;/code&gt; argument so you actually do not need to specify it. This version of the test is actually the Welch Student’s test, used when the variances of the populations are unknown and unequal. To test if two population variances are equal, you can use the Levene’s test (&lt;code&gt;leveneTest(dat3$value, dat3$sample)&lt;/code&gt; from the &lt;code&gt;{car}&lt;/code&gt; package, or simply by comparing the dispersion of the two samples via a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#dotplot&#34;&gt;dotplot&lt;/a&gt; or a boxplot). Note that the alternative hypothesis is &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu_1 - \mu_2 &amp;lt; 0\)&lt;/span&gt; so we need to add the argument &lt;code&gt;alternative = &#34;less&#34;&lt;/code&gt; as well:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- t.test(value ~ sample,
  data = dat3,
  var.equal = FALSE,
  alternative = &amp;quot;less&amp;quot;
)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Welch Two Sample t-test
## 
## data:  value by sample
## t = -3.0841, df = 8.2796, p-value = 0.007206
## alternative hypothesis: true difference in means between group 1 and group 2 is less than 0
## 95 percent confidence interval:
##        -Inf -0.3304098
## sample estimates:
## mean in group 1 mean in group 2 
##        0.420000        1.246667&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output above recaps all the information needed to perform the test (compare these results found in R with the results found by hand).&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value can be extracted as usual:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$p.value&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.00720603&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.007 so at the 5% significance level we reject the null hypothesis of equal means, meaning that we can conclude that the mean of population 1 is smaller than the mean of population 2. This result confirms what we found by hand.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;scenario-4-paired-samples-where-the-variance-of-the-differences-is-known-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 4: Paired samples where the variance of the differences is known&lt;/h2&gt;
&lt;p&gt;For the fourth scenario, suppose the data below. Moreover, suppose that the two samples are dependent (matched), that the variance of the differences in the population is known and equal to 1 (&lt;span class=&#34;math inline&#34;&gt;\(\sigma^2_D = 1\)&lt;/span&gt;) and that we would like to test whether the mean difference between the two populations is different than 0.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat4 &amp;lt;- data.frame(
  before = c(0.9, -0.8, 0.1, -0.3, 0.2),
  after = c(0.8, -0.9, -0.1, 0.4, 0.1)
)
dat4&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   before after
## 1    0.9   0.8
## 2   -0.8  -0.9
## 3    0.1  -0.1
## 4   -0.3   0.4
## 5    0.2   0.1&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat4$difference &amp;lt;- dat4$after - dat4$before

ggplot(dat4) +
  aes(y = difference) +
  geom_boxplot() +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios_files/figure-html/unnamed-chunk-27-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Since there is no function in R to perform a t-test with paired samples where the variance of the differences is known, here is one with arguments accepting:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the differences between the two samples (&lt;code&gt;x&lt;/code&gt;),&lt;/li&gt;
&lt;li&gt;the variance of the differences in the population (&lt;code&gt;V&lt;/code&gt;),&lt;/li&gt;
&lt;li&gt;the mean of the differences under the null hypothesis (&lt;code&gt;m0&lt;/code&gt;, default is &lt;code&gt;0&lt;/code&gt;),&lt;/li&gt;
&lt;li&gt;the significance level (&lt;code&gt;alpha&lt;/code&gt;, default is &lt;code&gt;0.05&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;and the alternative (&lt;code&gt;alternative&lt;/code&gt;, one of &lt;code&gt;&#34;two.sided&#34;&lt;/code&gt; (default), &lt;code&gt;&#34;less&#34;&lt;/code&gt; or &lt;code&gt;&#34;greater&#34;&lt;/code&gt;):&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;t.test_pairedknownvar &amp;lt;- function(x, V, m0 = 0, alpha = 0.05, alternative = &amp;quot;two.sided&amp;quot;) {
  M &amp;lt;- mean(x)
  n &amp;lt;- length(x)
  sigma &amp;lt;- sqrt(V)
  S &amp;lt;- sqrt(V / n)
  statistic &amp;lt;- (M - m0) / S
  p &amp;lt;- if (alternative == &amp;quot;two.sided&amp;quot;) {
    2 * pnorm(abs(statistic), lower.tail = FALSE)
  } else if (alternative == &amp;quot;less&amp;quot;) {
    pnorm(statistic, lower.tail = TRUE)
  } else {
    pnorm(statistic, lower.tail = FALSE)
  }
  LCL &amp;lt;- (M - S * qnorm(1 - alpha / 2))
  UCL &amp;lt;- (M + S * qnorm(1 - alpha / 2))
  value &amp;lt;- list(mean = M, m0 = m0, sigma = sigma, statistic = statistic, p.value = p, LCL = LCL, UCL = UCL, alternative = alternative)
  # print(sprintf(&amp;quot;P-value = %g&amp;quot;,p))
  # print(sprintf(&amp;quot;Lower %.2f%% Confidence Limit = %g&amp;quot;,
  #               alpha, LCL))
  # print(sprintf(&amp;quot;Upper %.2f%% Confidence Limit = %g&amp;quot;,
  #               alpha, UCL))
  return(value)
}

test &amp;lt;- t.test_pairedknownvar(dat4$after - dat4$before,
  V = 1
)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $mean
## [1] 0.04
## 
## $m0
## [1] 0
## 
## $sigma
## [1] 1
## 
## $statistic
## [1] 0.08944272
## 
## $p.value
## [1] 0.9287301
## 
## $LCL
## [1] -0.8365225
## 
## $UCL
## [1] 0.9165225
## 
## $alternative
## [1] &amp;quot;two.sided&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output above recaps all the information needed to perform the test (compare these results found in R with the results found by hand).&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value can be extracted as usual:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$p.value&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.9287301&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.929 so at the 5% significance level we do not reject the null hypothesis of the mean of the differences being equal to 0. There is no sufficient evidence in the data to reject the hypothesis that the mean difference between the two populations is equal to 0. This result confirms what we found by hand.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;scenario-5-paired-samples-where-the-variance-of-the-differences-is-unknown-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 5: Paired samples where the variance of the differences is unknown&lt;/h2&gt;
&lt;p&gt;For the fifth and final scenario, suppose the data below. Moreover, suppose that the two samples are dependent (matched), that the variance of the differences in the population is unknown and that we would like to test whether a treatment is effective in increasing running capabilities (the higher the value, the better in terms of running capabilities).&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat5 &amp;lt;- data.frame(
  before = c(9, 8, 1, 3, 2),
  after = c(16, 11, 15, 12, 9)
)
dat5&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   before after
## 1      9    16
## 2      8    11
## 3      1    15
## 4      3    12
## 5      2     9&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat5$difference &amp;lt;- dat5$after - dat5$before

ggplot(dat5) +
  aes(y = difference) +
  geom_boxplot() +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios_files/figure-html/unnamed-chunk-31-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;There is a function in R for this version of the test, and it is simply the &lt;code&gt;t.test()&lt;/code&gt; function with the &lt;code&gt;paired = TRUE&lt;/code&gt; argument. This version of the test is actually the standard version of the Student’s t-test with paired samples. Note that the alternative hypothesis is &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu_D &amp;gt; 0\)&lt;/span&gt; so we need to add the argument &lt;code&gt;alternative = &#34;greater&#34;&lt;/code&gt; as well:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- t.test(dat5$after, dat5$before,
  alternative = &amp;quot;greater&amp;quot;,
  paired = TRUE
)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Paired t-test
## 
## data:  dat5$after and dat5$before
## t = 4.4721, df = 4, p-value = 0.005528
## alternative hypothesis: true mean difference is greater than 0
## 95 percent confidence interval:
##  4.186437      Inf
## sample estimates:
## mean difference 
##               8&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that we wrote &lt;code&gt;after&lt;/code&gt; and then &lt;code&gt;before&lt;/code&gt; in this order. If you write &lt;code&gt;before&lt;/code&gt; and then &lt;code&gt;after&lt;/code&gt;, make sure to change the alternative to &lt;code&gt;alternative = &#34;less&#34;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;If your data is in the long format, use the tilde &lt;code&gt;~&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat5 &amp;lt;- data.frame(
  value = c(9, 8, 1, 3, 2, 16, 11, 15, 12, 9),
  time = c(rep(&amp;quot;before&amp;quot;, 5), rep(&amp;quot;after&amp;quot;, 5))
)
dat5&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    value   time
## 1      9 before
## 2      8 before
## 3      1 before
## 4      3 before
## 5      2 before
## 6     16  after
## 7     11  after
## 8     15  after
## 9     12  after
## 10     9  after&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- t.test(value ~ time,
  data = dat5,
  alternative = &amp;quot;greater&amp;quot;,
  paired = TRUE
)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Paired t-test
## 
## data:  value by time
## t = 4.4721, df = 4, p-value = 0.005528
## alternative hypothesis: true mean difference is greater than 0
## 95 percent confidence interval:
##  4.186437      Inf
## sample estimates:
## mean difference 
##               8&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output above recaps all the information needed to perform the test (compare these results found in R with the results found by hand).&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value can be extracted as usual:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$p.value&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.005528247&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.006 so at the 5% significance level we reject the null hypothesis of the mean of the differences being equal to 0, meaning that we can conclude that the treatment is effective in increasing the running capabilities (because the mean of the differences is greater than 0). This result confirms what we found by hand.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;combination-of-plot-and-statistical-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Combination of plot and statistical test&lt;/h2&gt;
&lt;p&gt;After having written this article, I discovered the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package which I believe is worth mentioning here, in particular the &lt;code&gt;ggbetweenstats()&lt;/code&gt; and &lt;code&gt;ggwithinstats()&lt;/code&gt; functions for independent and paired samples, respectively.&lt;/p&gt;
&lt;p&gt;These two functions combine a boxplot—representing the distribution for each group—and the results of the statistical test displayed in the subtitle of the plot.&lt;/p&gt;
&lt;p&gt;See examples below for scenarios 2, 3 and 5. Unfortunately, the package does not allow to run tests for scenarios 1 and 4.&lt;/p&gt;
&lt;div id=&#34;scenario-2-independent-samples-with-2-equal-but-unknown-variances-2&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Scenario 2: Independent samples with 2 equal but unknown variances&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;ggbetweenstats()&lt;/code&gt; function is used for independent samples:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load package
library(ggstatsplot)
library(ggplot2)

# plot with statistical results
ggbetweenstats(
  data = dat2bis,
  x = sample,
  y = value,
  plot.type = &amp;quot;box&amp;quot;, # for boxplot
  type = &amp;quot;parametric&amp;quot;, # for student&amp;#39;s t-test
  var.equal = TRUE, # equal variances
  centrality.plotting = FALSE # remove mean
) +
  labs(caption = NULL) # remove caption&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios_files/figure-html/unnamed-chunk-35-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is displayed after &lt;code&gt;p =&lt;/code&gt; in the subtitle of the plot. Based on this plot and the &lt;em&gt;p&lt;/em&gt;-value being lower than 5% (&lt;em&gt;p&lt;/em&gt;-value = 0.008), we reject the null hypothesis that the two population means are equal.&lt;/p&gt;
&lt;p&gt;Note that, the &lt;em&gt;p&lt;/em&gt;-value is two times as large as the one obtained with the &lt;code&gt;t.test()&lt;/code&gt; function because when we ran &lt;code&gt;t.test()&lt;/code&gt; we specified &lt;code&gt;alternative = &#34;greater&#34;&lt;/code&gt; (i.e., a one-sided test). In our plot with the &lt;code&gt;ggbetweenstats()&lt;/code&gt; function, it is a two-sided test that is performed by default, that is, &lt;code&gt;alternative = &#34;two.sided&#34;&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;scenario-3-independent-samples-with-2-unequal-and-unknown-variances-2&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Scenario 3: Independent samples with 2 unequal and unknown variances&lt;/h3&gt;
&lt;p&gt;We also have independent samples so we use the &lt;code&gt;ggbetweenstats()&lt;/code&gt; function again, but this time the two populations variances are not assumed to be equal so we specify the argument &lt;code&gt;var.equal = FALSE&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# plot with statistical results
ggbetweenstats(
  data = dat3,
  x = sample,
  y = value,
  plot.type = &amp;quot;box&amp;quot;, # for boxplot
  type = &amp;quot;parametric&amp;quot;, # for student&amp;#39;s t-test
  var.equal = FALSE, # unequal variances
  centrality.plotting = FALSE # remove mean
) +
  labs(caption = NULL) # remove caption&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios_files/figure-html/unnamed-chunk-36-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Based on the output, we reject the null hypothesis that the two population means are equal (&lt;em&gt;p&lt;/em&gt;-value = 0.01).&lt;/p&gt;
&lt;p&gt;Note that the &lt;em&gt;p&lt;/em&gt;-value displayed in the subtitle of the plot is also two times larger than with the &lt;code&gt;t.test()&lt;/code&gt; function for the same reason than above.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;scenario-5-paired-samples-where-the-variance-of-the-differences-is-unknown-2&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Scenario 5: Paired samples where the variance of the differences is unknown&lt;/h3&gt;
&lt;p&gt;In this case, the samples are paired so we use the &lt;code&gt;ggwithinstats()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggwithinstats(
  data = dat5,
  x = time,
  y = value,
  type = &amp;quot;parametric&amp;quot;, # for student&amp;#39;s t-test
  centrality.plotting = FALSE # remove mean
) +
  labs(caption = NULL) # remove caption&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios_files/figure-html/unnamed-chunk-38-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Based on the output, we reject the null hypothesis that mean of the differences between the two populations is equal to 0 (&lt;em&gt;p&lt;/em&gt;-value = 0.01).&lt;/p&gt;
&lt;p&gt;Again the &lt;em&gt;p&lt;/em&gt;-value in the subtitle of the plot is twice the one obtained with the &lt;code&gt;t.test()&lt;/code&gt; function for the same reason than above.&lt;/p&gt;
&lt;p&gt;The point of this section was to illustrate how to easily draw plots together with statistical results, which is exactly the aim of the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package. See more details and examples in this &lt;a href=&#34;https://statsandr.com/blog/how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way/&#34;&gt;article&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;assumptions&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Assumptions&lt;/h1&gt;
&lt;p&gt;As for many &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt;, there are some assumptions that need to be met in order to be able to interpret the results. When one or several of them are not met, although it is technically possible to perform these tests, it would be incorrect to interpret the results or trust the conclusions.&lt;/p&gt;
&lt;p&gt;Below are the assumptions of the Student’s t-test for two samples, how to test them and which other tests exist if an assumption is not met:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Variable type&lt;/strong&gt;: A Student’s t-test requires a mix of one &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#quantitative&#34;&gt;quantitative&lt;/a&gt; dependent variable (which corresponds to the measurements to which the question relates) and one &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;qualitative&lt;/a&gt; independent variable (with exactly 2 levels which will determine the groups to compare).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Independence&lt;/strong&gt;: The data, collected from a representative and randomly selected portion of the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;population&lt;/a&gt;, should be independent between groups and within each group. The assumption of independence is most often verified based on the design of the experiment and on the good control of experimental conditions rather than via a formal test. If you are still unsure about independence based on the experiment design, ask yourself if one observation is related to another (if one observation has an impact on another) within each group or between the groups themselves. If not, it is most likely that you have independent &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;samples&lt;/a&gt;. If observations between samples (forming the different groups to be compared) are dependent (for example, if two measurements have been collected on the &lt;strong&gt;same individuals&lt;/strong&gt; as it is often the case in medical studies when measuring a metric (i) before and (ii) after a treatment), the paired version of the Student’s t-test, called the Student’s t-test for paired samples, should be preferred in order to take into account the dependency between the two groups to be compared.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Normality&lt;/strong&gt;:
&lt;ul&gt;
&lt;li&gt;With small samples (usually &lt;span class=&#34;math inline&#34;&gt;\(n &amp;lt; 30\)&lt;/span&gt;), when the two samples are independent, observations in &lt;strong&gt;both samples&lt;/strong&gt; should follow a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;&lt;strong&gt;normal distribution&lt;/strong&gt;&lt;/a&gt;. When using the Student’s t-test for paired samples, it is the difference between the observations of the two samples that should follow a normal distribution. The normality assumption can be tested visually thanks to a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt; and a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#qq-plot&#34;&gt;QQ-plot&lt;/a&gt;, and/or formally via a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#normality-test&#34;&gt;normality test&lt;/a&gt; such as the Shapiro-Wilk or Kolmogorov-Smirnov test. If, even after a transformation (e.g., logarithmic transformation, square root, etc.), your data still do not follow a normal distribution, the &lt;a href=&#34;https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/&#34;&gt;Wilcoxon test&lt;/a&gt; (&lt;code&gt;wilcox.test(variable1 ~ variable2, data = dat&lt;/code&gt; in R) can be applied. This non-parametric test, robust to non normal distributions, compares the medians instead of the means in order to compare the two populations.&lt;/li&gt;
&lt;li&gt;With large samples (usually &lt;span class=&#34;math inline&#34;&gt;\(n \ge 30\)&lt;/span&gt;), &lt;strong&gt;normality of the data is not required&lt;/strong&gt; (this is a common misconception!). By the &lt;a href=&#34;https://en.wikipedia.org/wiki/Central_limit_theorem&#34; target=&#34;_blank&#34;&gt;central limit theorem&lt;/a&gt;, sample means of large samples are often well-approximated by a normal distribution even if the data are not normally distributed &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-stevens2013intermediate&#34; role=&#34;doc-biblioref&#34;&gt;Stevens 2013&lt;/a&gt;)&lt;/span&gt;. It is therefore not required to test the normality assumption when the number of observations in each group/sample is large.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Equality of variances&lt;/strong&gt;: When the two samples are independent, the variances of the two groups should be equal in the populations (an assumption called &lt;strong&gt;homogeneity of the variances&lt;/strong&gt;, or even sometimes referred as homoscedasticity, as opposed to heteroscedasticity if variances are different across groups). This assumption can be tested graphically (by comparing the dispersion in a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#boxplot&#34;&gt;boxplot&lt;/a&gt; or &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#dotplot&#34;&gt;dotplot&lt;/a&gt; for instance), or more formally via the Levene’s test (&lt;code&gt;leveneTest(variable ~ group)&lt;/code&gt; from the &lt;code&gt;{car}&lt;/code&gt; package) or via a F test (&lt;code&gt;var.test(variable ~ group)&lt;/code&gt;). If the hypothesis of equal variances is rejected, another version of the Student’s t-test can be used: the Welch test (&lt;code&gt;t.test(variable ~ group, var.equal = FALSE)&lt;/code&gt;). Note that the Welch test does not require homogeneity of the variances, but the distributions should still follow a normal distribution in case of small sample sizes. If your distributions are not normally distributed or the variances are unequal, the &lt;a href=&#34;https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/&#34;&gt;Wilcoxon test&lt;/a&gt; should be used. This test does not require the assumptions of normality nor homoscedasticity of the variances.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Outliers&lt;/strong&gt;: An &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outlier&lt;/a&gt; is a value or an observation that is distant from the other observations. There should be &lt;strong&gt;no significant outliers in the two groups&lt;/strong&gt;, or the conclusions of your t-test may be flawed. There are several methods to &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;detect outliers&lt;/a&gt; in your data but in order to deal with them, it is your choice to either:
&lt;ul&gt;
&lt;li&gt;use the non-parametric version (i.e., the &lt;a href=&#34;https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/&#34;&gt;Wilcoxon test&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;transform your data (logarithmic or Box-Cox transformation, among others)&lt;/li&gt;
&lt;li&gt;or remove them (be careful)&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;This concludes a relatively long article. Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to understand how the different versions of the Student’s t-test for two samples work and how to perform them by hand and in R. If you are interested, here is a &lt;a href=&#34;https://statsandr.com/blog/a-shiny-app-for-inferential-statistics-by-hand/&#34;&gt;Shiny app&lt;/a&gt; to perform these tests by hand easily (you just need to enter your data and select the appropriate version of the test thanks to the sidebar menu).&lt;/p&gt;
&lt;p&gt;Moreover, I invite you to read:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;this &lt;a href=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r-test-on-one-mean/&#34;&gt;article&lt;/a&gt; if you would like to know how to compute the Student’s t-test but this time, for one sample,&lt;/li&gt;
&lt;li&gt;this &lt;a href=&#34;https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/&#34;&gt;article&lt;/a&gt; if you would like to compare 2 groups under the non-normality assumption, or&lt;/li&gt;
&lt;li&gt;this &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;article&lt;/a&gt; if you would like to use an ANOVA to compare 3 or more groups.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-rowntree2000statistics&#34; class=&#34;csl-entry&#34;&gt;
Rowntree, Derek. 2000. &lt;em&gt;Statistics Without Tears&lt;/em&gt;.
&lt;/div&gt;
&lt;div id=&#34;ref-stevens2013intermediate&#34; class=&#34;csl-entry&#34;&gt;
Stevens, James P. 2013. &lt;em&gt;Intermediate Statistics: A Modern Approach&lt;/em&gt;. Routledge.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;Remind that inferential statistics, as opposed to &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics&lt;/a&gt;, is a branch of statistics defined as the science of drawing conclusions about a population from observations made on a representative sample of that population. See the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;difference between population and sample&lt;/a&gt;.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;For the rest of the present article, when we write Student’s t-test, we refer to the case of 2 samples. See &lt;a href=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r-test-on-one-mean/&#34;&gt;one sample t-test&lt;/a&gt; if you want to compare only one sample.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;It is a least the case for parametric hypothesis tests. A parametric test means that it is based on a theoretical statistical distribution, which depends on some defined parameters. In the case of the Student’s t-test for two samples, it is based on the Student’s t distribution with a single parameter, the degrees of freedom (&lt;span class=&#34;math inline&#34;&gt;\(df = n_1 + n_2 - 2\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(n_1\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(n_2\)&lt;/span&gt; are the two sample sizes), or the normal distribution.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;Thanks gmacar for pointing it out to me.&lt;a href=&#34;#fnref4&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Correlogram in R: how to highlight the most correlated variables in a dataset</title>
      <link>https://statsandr.com/blog/correlogram-in-r-how-to-highlight-the-most-correlated-variables-in-a-dataset/</link>
      <pubDate>Sat, 22 Feb 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/correlogram-in-r-how-to-highlight-the-most-correlated-variables-in-a-dataset/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#correlation-matrix&#34; id=&#34;toc-correlation-matrix&#34;&gt;Correlation matrix&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#correlogram&#34; id=&#34;toc-correlogram&#34;&gt;Correlogram&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#correlation-test&#34; id=&#34;toc-correlation-test&#34;&gt;Correlation test&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#code&#34; id=&#34;toc-code&#34;&gt;Code&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#ggstatsplot-package&#34; id=&#34;toc-ggstatsplot-package&#34;&gt;&lt;code&gt;{ggstatsplot}&lt;/code&gt; package&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#lares-package&#34; id=&#34;toc-lares-package&#34;&gt;&lt;code&gt;{lares}&lt;/code&gt; package&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#all-possible-correlations&#34; id=&#34;toc-all-possible-correlations&#34;&gt;All possible correlations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#correlation-of-one-variable-against-all-others&#34; id=&#34;toc-correlation-of-one-variable-against-all-others&#34;&gt;Correlation of one variable against all others&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/correlogram-in-r-how-to-highlight-correlations-between-variables_files/correlogram-in-r-how-to-highlight-correlations-between-variables.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;&lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;Correlation&lt;/a&gt;, often computed as part of &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt;, is a statistical tool used to study the relationship between two variables, that is, whether and how strongly couples of variables are associated.&lt;/p&gt;
&lt;p&gt;Correlations are measured between 2 variables at a time. Therefore, for datasets with many variables, computing correlations can become quite cumbersome and time consuming.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;correlation-matrix&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Correlation matrix&lt;/h1&gt;
&lt;p&gt;A solution to this problem is to compute correlations and display them in a correlation matrix, which shows correlation coefficients for all possible combinations of two variables in the dataset.&lt;/p&gt;
&lt;p&gt;For example, below is the correlation matrix for the dataset &lt;code&gt;mtcars&lt;/code&gt; (which, as described by the help documentation of R, comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles).&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; For this article, we include only the &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#continuous&#34;&gt;continuous&lt;/a&gt; variables.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- mtcars[, c(1, 3:7)]
round(cor(dat), 2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##        mpg  disp    hp  drat    wt  qsec
## mpg   1.00 -0.85 -0.78  0.68 -0.87  0.42
## disp -0.85  1.00  0.79 -0.71  0.89 -0.43
## hp   -0.78  0.79  1.00 -0.45  0.66 -0.71
## drat  0.68 -0.71 -0.45  1.00 -0.71  0.09
## wt   -0.87  0.89  0.66 -0.71  1.00 -0.17
## qsec  0.42 -0.43 -0.71  0.09 -0.17  1.00&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Even after rounding the correlation coefficients to 2 digits, you will conceive that this correlation matrix is not easily and quickly interpretable.&lt;/p&gt;
&lt;p&gt;If you are using &lt;a href=&#34;https://statsandr.com/blog/getting-started-in-r-markdown/&#34;&gt;R Markdown&lt;/a&gt;, you can use the &lt;code&gt;pander()&lt;/code&gt; function from the &lt;code&gt;{pander}&lt;/code&gt; package to make it slightly more readable, but still, we must admit that this table is not optimal when it comes to visualizing correlations between several variables of a dataset, especially for large datasets.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;correlogram&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Correlogram&lt;/h1&gt;
&lt;p&gt;To tackle this issue and make it much more insightful, let’s transform the correlation matrix into a correlation plot. A correlation plot (also referred as a correlogram or corrgram in &lt;span class=&#34;citation&#34;&gt;Friendly (&lt;a href=&#34;#ref-friendly2002corrgrams&#34;&gt;2002&lt;/a&gt;)&lt;/span&gt;) allows to highlight the variables that are most (positively and negatively) correlated. Below an example with the same dataset presented above:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/correlogram-in-r-how-to-highlight-correlations-between-variables_files/figure-html/unnamed-chunk-2-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The correlogram represents the correlations for all pairs of variables. Positive correlations are displayed in blue and negative correlations in red. The intensity of the color is proportional to the correlation coefficient so the stronger the correlation (i.e., the closer to -1 or 1), the darker the boxes. The color legend on the right hand side of the correlogram shows the correlation coefficients and the corresponding colors.&lt;/p&gt;
&lt;p&gt;As a reminder, a negative correlation implies that the two variables under consideration vary in opposite directions, that is, if one variable increases the other decreases and vice versa. A positive correlation implies that the two variables under consideration vary in the same direction, that is, if one variable increases the other increases and if one variable decreases the other decreases as well. Furthermore, the stronger the correlation, the stronger the association between the two variables.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;correlation-test&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Correlation test&lt;/h1&gt;
&lt;p&gt;Finally, a white box in the correlogram indicates that the correlation is not significantly different from 0 at the specified significance level (in this example, at &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 5\)&lt;/span&gt;%) for the couple of variables. A correlation not significantly different from 0 means that there is &lt;strong&gt;no linear&lt;/strong&gt; relationship between the two variables considered in the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;population&lt;/a&gt; (there could be another kind of association, but not linear).&lt;/p&gt;
&lt;p&gt;To determine whether a specific correlation coefficient is significantly different from 0, a &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;correlation test&lt;/a&gt; has been performed. Remind that the null and alternative hypotheses of this test are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\rho = 0\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\rho \ne 0\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(\rho\)&lt;/span&gt; is denotes the correlation. The correlation test is based on two factors: the number of observations and the correlation coefficient. The more observations and the stronger the correlation between 2 variables, the more likely it is to reject the null hypothesis of no correlation between these 2 variables.&lt;/p&gt;
&lt;p&gt;In the context of our example, the correlogram above shows that the variables &lt;code&gt;wt&lt;/code&gt; (weight) and &lt;code&gt;hp&lt;/code&gt; (horsepower) are positively correlated, while the variables &lt;code&gt;mpg&lt;/code&gt; (miles per gallon) and &lt;code&gt;wt&lt;/code&gt; (weight) are negatively correlated (both correlations make sense if we think about it). Furthermore, the variables &lt;code&gt;wt&lt;/code&gt; and &lt;code&gt;qsec&lt;/code&gt; are not correlated (indicated by a white box). Even if the correlation coefficient is -0.17 between the 2 variables, the correlation test has shown that we cannot reject the hypothesis of no correlation in the population. This is the reason the box for these two variable is white.&lt;/p&gt;
&lt;p&gt;Although this correlogram presents exactly the same information than the correlation matrix, the correlogram presents a visual representation of the correlation matrix, allowing to quickly scan through it to see which variables are correlated and which are not.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;code&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Code&lt;/h1&gt;
&lt;p&gt;For those interested to draw this correlogram with their own data, here is the code of the function I adapted based on the &lt;code&gt;corrplot()&lt;/code&gt; function from the &lt;code&gt;{corrplot}&lt;/code&gt; package (thanks again to all contributors of this package):&lt;/p&gt;
&lt;script src=&#34;https://gist.github.com/AntoineSoetewey/1fc0fe939336a8b8085e1872e045b48f.js&#34;&gt;&lt;/script&gt;
&lt;p&gt;The main arguments in the &lt;code&gt;corrplot2()&lt;/code&gt; function are the following:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;data&lt;/code&gt;: name of your dataset&lt;/li&gt;
&lt;li&gt;&lt;code&gt;method&lt;/code&gt;: the correlation method to be computed, one of “pearson” (default), “kendall”, or “spearman”. As a rule of thumb, if your dataset contains &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#continuous&#34;&gt;quantitative continuous&lt;/a&gt; variables that have a linear relationship, you can keep the Pearson method. If you have &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#ordinal&#34;&gt;qualitative ordinal&lt;/a&gt; variables or quantitative variables with a partially linear link, the Spearman method is more appropriate&lt;/li&gt;
&lt;li&gt;&lt;code&gt;sig.level&lt;/code&gt;: the significance level for the correlation test, default is 0.05&lt;/li&gt;
&lt;li&gt;&lt;code&gt;order&lt;/code&gt;: order of the variables, one of “original” (default), “AOE” (angular order of the eigenvectors), “FPC” (first principal component order), “hclust” (hierarchical clustering order), “alphabet” (alphabetical order)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;diag&lt;/code&gt;: display the correlation coefficients on the diagonal? The default is &lt;code&gt;FALSE&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;type&lt;/code&gt;: display the entire correlation matrix or simply the upper/lower part, one of “upper” (default), “lower”, “full”&lt;/li&gt;
&lt;li&gt;&lt;code&gt;tl.srt&lt;/code&gt;: rotation of the variable labels&lt;/li&gt;
&lt;li&gt;(note that missing values in the dataset are automatically removed)&lt;/li&gt;
&lt;/ul&gt;
&lt;!-- You can also play with the arguments of the `corrplot2` function and see the results thanks to this [R Shiny app](https://antoinesoetewey.shinyapps.io/correlogram/){target=&#34;_blank&#34;}. --&gt;
&lt;/div&gt;
&lt;div id=&#34;ggstatsplot-package&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;&lt;code&gt;{ggstatsplot}&lt;/code&gt; package&lt;/h1&gt;
&lt;p&gt;An alternative to the correlogram presented above is possible with the &lt;code&gt;ggcorrmat()&lt;/code&gt; function from the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load package
library(ggstatsplot)

# correlogram
ggstatsplot::ggcorrmat(
  data = dat,
  type = &amp;quot;parametric&amp;quot;, # parametric for Pearson, nonparametric for Spearman&amp;#39;s correlation
  colors = c(&amp;quot;darkred&amp;quot;, &amp;quot;white&amp;quot;, &amp;quot;steelblue&amp;quot;) # change default colors
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/correlogram-in-r-how-to-highlight-correlations-between-variables_files/figure-html/unnamed-chunk-3-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In this correlogram, the non-significant correlations (by default at the 5% significance level with the Holm adjustment method) are shown by a cross on the correlation coefficients.&lt;/p&gt;
&lt;p&gt;The advantage of this alternative compared to the previous one is that it is directly available within a package, so you do not need to run the code of the function first in order to draw the correlogram.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;lares-package&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;&lt;code&gt;{lares}&lt;/code&gt; package&lt;/h1&gt;
&lt;p&gt;Thanks to this article, I discovered the &lt;code&gt;{lares}&lt;/code&gt; package which has really nice features regarding plotting correlations. Another advantage of this package is that it can be used to compute correlations with numerical, logical, categorical and date variables.&lt;/p&gt;
&lt;p&gt;See more information about the package in this &lt;a href=&#34;https://datascienceplus.com/find-insights-with-ranked-cross-correlations/&#34; target=&#34;_blank&#34;&gt;article&lt;/a&gt;.&lt;/p&gt;
&lt;div id=&#34;all-possible-correlations&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;All possible correlations&lt;/h2&gt;
&lt;p&gt;Use the &lt;code&gt;corr_cross()&lt;/code&gt; function if you want to compute all correlations and return the highest and significant ones in a plot:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# devtools::install_github(&amp;quot;laresbernardo/lares&amp;quot;)
library(lares)

corr_cross(dat, # name of dataset
  max_pvalue = 0.05, # display only significant correlations (at 5% level)
  top = 10 # display top 10 couples of variables (by correlation coefficient)
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/correlogram-in-r-how-to-highlight-correlations-between-variables_files/figure-html/unnamed-chunk-4-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Negative correlations are represented in red and positive correlations in blue.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;correlation-of-one-variable-against-all-others&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Correlation of one variable against all others&lt;/h2&gt;
&lt;p&gt;Use the &lt;code&gt;corr_var()&lt;/code&gt; function if you want to focus on the correlation of one variable against all others, and return the highest ones in a plot:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;corr_var(dat, # name of dataset
  mpg, # name of variable to focus on
  top = 5 # display top 5 correlations
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/correlogram-in-r-how-to-highlight-correlations-between-variables_files/figure-html/unnamed-chunk-5-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article will help you to visualize correlations between variables in a dataset and to make correlation matrices more insightful and more appealing.&lt;/p&gt;
&lt;p&gt;If you want to learn more about this topic, see:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;how to &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;compute correlation coefficients and perform correlation tests in R&lt;/a&gt;, or&lt;/li&gt;
&lt;li&gt;how to &lt;a href=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/&#34;&gt;compute correlation coefficients by hand&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-friendly2002corrgrams&#34; class=&#34;csl-entry&#34;&gt;
Friendly, Michael. 2002. &lt;span&gt;“Corrgrams: Exploratory Displays for Correlation Matrices.”&lt;/span&gt; &lt;em&gt;The American Statistician&lt;/em&gt; 56 (4): 316–24.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;The dataset &lt;code&gt;mtcars&lt;/code&gt; is preloaded in R by default, so there is no need to import it into R. Check the article “&lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/&#34;&gt;How to import an Excel file in R&lt;/a&gt;” if you need help in importing your own dataset.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>The complete guide to clustering analysis: k-means and hierarchical clustering by hand and in R</title>
      <link>https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r/</link>
      <pubDate>Thu, 13 Feb 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#what-is-clustering-analysis&#34; id=&#34;toc-what-is-clustering-analysis&#34;&gt;What is clustering analysis?&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#application-1-computing-distances&#34; id=&#34;toc-application-1-computing-distances&#34;&gt;Application 1: Computing distances&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#solution&#34; id=&#34;toc-solution&#34;&gt;Solution&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#k-means-clustering&#34; id=&#34;toc-k-means-clustering&#34;&gt;&lt;em&gt;k&lt;/em&gt;-means clustering&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#application-2-k-means-clustering&#34; id=&#34;toc-application-2-k-means-clustering&#34;&gt;Application 2: &lt;em&gt;k&lt;/em&gt;-means clustering&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#data&#34; id=&#34;toc-data&#34;&gt;Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#kmeans-with-2-groups&#34; id=&#34;toc-kmeans-with-2-groups&#34;&gt;&lt;code&gt;kmeans()&lt;/code&gt; with 2 groups&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#quality-of-a-k-means-partition&#34; id=&#34;toc-quality-of-a-k-means-partition&#34;&gt;Quality of a &lt;em&gt;k&lt;/em&gt;-means partition&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#nstart-for-several-initial-centers-and-better-stability&#34; id=&#34;toc-nstart-for-several-initial-centers-and-better-stability&#34;&gt;&lt;code&gt;nstart&lt;/code&gt; for several initial centers and better stability&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#kmeans-with-3-groups&#34; id=&#34;toc-kmeans-with-3-groups&#34;&gt;&lt;code&gt;kmeans()&lt;/code&gt; with 3 groups&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#optimal-number-of-clusters&#34; id=&#34;toc-optimal-number-of-clusters&#34;&gt;Optimal number of clusters&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#elbow-method&#34; id=&#34;toc-elbow-method&#34;&gt;Elbow method&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#silhouette-method&#34; id=&#34;toc-silhouette-method&#34;&gt;Silhouette method&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#gap-statistic-method&#34; id=&#34;toc-gap-statistic-method&#34;&gt;Gap statistic method&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#consensus-based-algorithm&#34; id=&#34;toc-consensus-based-algorithm&#34;&gt;Consensus-based algorithm&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#visualizations&#34; id=&#34;toc-visualizations&#34;&gt;Visualizations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#manual-application-and-verification-in-r&#34; id=&#34;toc-manual-application-and-verification-in-r&#34;&gt;Manual application and verification in R&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#solution-by-hand&#34; id=&#34;toc-solution-by-hand&#34;&gt;Solution by hand&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#solution-in-r&#34; id=&#34;toc-solution-in-r&#34;&gt;Solution in R&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#hierarchical-clustering&#34; id=&#34;toc-hierarchical-clustering&#34;&gt;Hierarchical clustering&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#application-3-hierarchical-clustering&#34; id=&#34;toc-application-3-hierarchical-clustering&#34;&gt;Application 3: hierarchical clustering&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#data-1&#34; id=&#34;toc-data-1&#34;&gt;Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#solution-by-hand-1&#34; id=&#34;toc-solution-by-hand-1&#34;&gt;Solution by hand&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#single-linkage&#34; id=&#34;toc-single-linkage&#34;&gt;Single linkage&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#complete-linkage&#34; id=&#34;toc-complete-linkage&#34;&gt;Complete linkage&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#average-linkage&#34; id=&#34;toc-average-linkage&#34;&gt;Average linkage&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#solution-in-r-1&#34; id=&#34;toc-solution-in-r-1&#34;&gt;Solution in R&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#single-linkage-1&#34; id=&#34;toc-single-linkage-1&#34;&gt;Single linkage&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#optimal-number-of-clusters-1&#34; id=&#34;toc-optimal-number-of-clusters-1&#34;&gt;Optimal number of clusters&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#complete-linkage-1&#34; id=&#34;toc-complete-linkage-1&#34;&gt;Complete linkage&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#average-linkage-1&#34; id=&#34;toc-average-linkage-1&#34;&gt;Average linkage&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#k-means-versus-hierarchical-clustering&#34; id=&#34;toc-k-means-versus-hierarchical-clustering&#34;&gt;&lt;em&gt;k&lt;/em&gt;-means versus hierarchical clustering&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#whats-next&#34; id=&#34;toc-whats-next&#34;&gt;What’s next?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r-statsandr.com.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note that this article is inspired from the lecture notes of Prof. Johan Segers and my personal notes as teaching assistant for his course entitled “Multivariate statistical analysis” given at UCLouvain.&lt;/em&gt;&lt;/p&gt;
&lt;div id=&#34;what-is-clustering-analysis&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;What is clustering analysis?&lt;/h1&gt;
&lt;p&gt;Clustering analysis is a form of exploratory data analysis in which observations are divided into different groups that share common characteristics.&lt;/p&gt;
&lt;p&gt;The purpose of cluster analysis (also known as classification) is to construct groups (or classes or &lt;em&gt;clusters&lt;/em&gt;) while ensuring the following property: &lt;strong&gt;within a group&lt;/strong&gt; the observations must be as &lt;strong&gt;similar&lt;/strong&gt; as possible (intracluster similarity), while observations belonging to &lt;strong&gt;different groups&lt;/strong&gt; must be as &lt;strong&gt;different&lt;/strong&gt; as possible (intercluster similarity).&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/intercluster-intracluster-distance.png&#34; style=&#34;width:100.0%&#34; alt=&#34;An illustration of intercluster and intracluster distance. Source: dinhanhthi.com&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;An illustration of intercluster and intracluster distance. Source: dinhanhthi.com&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The two most common types of classification are:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;em&gt;k&lt;/em&gt;-means clustering&lt;/li&gt;
&lt;li&gt;Hierarchical clustering&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The first is generally used when the &lt;strong&gt;number of classes is fixed&lt;/strong&gt; in advance, while the second is generally used for an &lt;strong&gt;unknown number of classes&lt;/strong&gt; and helps to determine this optimal number. For this reason, &lt;em&gt;k&lt;/em&gt;-means is considered as a supervised technique, while hierarchical clustering is considered as an unsupervised technique because the estimation of the number of clusters is part of the algorithm. See more clustering methods in this &lt;a href=&#34;https://easystats.github.io/parameters/articles/clustering.html&#34; target=&#34;_blank&#34;&gt;article&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Both methods are illustrated below through applications by hand and in R. Note that for hierarchical clustering, only the &lt;em&gt;ascending&lt;/em&gt; classification is presented in this article.&lt;/p&gt;
&lt;p&gt;Clustering algorithms use the &lt;strong&gt;distance&lt;/strong&gt; in order to separate observations into different groups. Therefore, before diving into the presentation of the two classification methods, a reminder exercise on how to compute distances between points is presented.&lt;/p&gt;
&lt;div id=&#34;application-1-computing-distances&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Application 1: Computing distances&lt;/h2&gt;
&lt;p&gt;Let a data set containing the points &lt;span class=&#34;math inline&#34;&gt;\(\boldsymbol{a} = (0, 0)&amp;#39;\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(\boldsymbol{b} = (1, 0)&amp;#39;\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\boldsymbol{c} = (5, 5)&amp;#39;\)&lt;/span&gt;. Compute the matrix of Euclidean distances between the points by hand and in R.&lt;/p&gt;
&lt;div id=&#34;solution&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Solution&lt;/h3&gt;
&lt;p&gt;The points are as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# We create the points in R
a &amp;lt;- c(0, 0)
b &amp;lt;- c(1, 0)
c &amp;lt;- c(5, 5)

X &amp;lt;- rbind(a, b, c) # a, b and c are combined per row
colnames(X) &amp;lt;- c(&amp;quot;x&amp;quot;, &amp;quot;y&amp;quot;) # rename columns

X # display the points&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   x y
## a 0 0
## b 1 0
## c 5 5&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By the Pythagorean theorem, we will remember that the distance between 2 points &lt;span class=&#34;math inline&#34;&gt;\((x_a, y_a)\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\((x_b, y_b)\)&lt;/span&gt; in &lt;span class=&#34;math inline&#34;&gt;\(\mathbb{R}^2\)&lt;/span&gt; is given by &lt;span class=&#34;math inline&#34;&gt;\(\sqrt{(x_a - x_b)^2 + (y_a - y_b)^2}\)&lt;/span&gt;. So for instance, for the distance between the points &lt;span class=&#34;math inline&#34;&gt;\(\boldsymbol{b} = (1, 0)&amp;#39;\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\boldsymbol{c} = (5, 5)&amp;#39;\)&lt;/span&gt; presented in the statement above, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{equation}
  \begin{split}
        d(b, c) &amp;amp;= \sqrt{(x_b - x_c)^2 + (y_b - y_c)^2} \\
        &amp;amp;= \sqrt{(1-5)^2 + (0-5)^2}\\
        &amp;amp;= 6.403124
  \end{split}
\end{equation}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;We can proceed similarly for all pairs of points to find the distance matrix by hand. In R, the &lt;code&gt;dist()&lt;/code&gt; function allows you to find the distance of points in a matrix or dataframe in a very simple way:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# The distance is found using the dist() function:
distance &amp;lt;- dist(X, method = &amp;quot;euclidean&amp;quot;)
distance # display the distance matrix&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##          a        b
## b 1.000000         
## c 7.071068 6.403124&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the argument &lt;code&gt;method = &#34;euclidean&#34;&lt;/code&gt; is not mandatory because the Euclidean method is the default one.&lt;/p&gt;
&lt;p&gt;The distance matrix resulting from the &lt;code&gt;dist()&lt;/code&gt; function gives the distance between the different points. The Euclidean distance between the points &lt;span class=&#34;math inline&#34;&gt;\(\boldsymbol{b}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\boldsymbol{c}\)&lt;/span&gt; is 6.403124, which corresponds to what we found above via the Pythagorean formula.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: If two variables do not have the same units, one may have more weight in the calculation of the Euclidean distance than the other. In that case, it is preferable to scale the data. Scaling data allows to obtain variables independent of their unit, and this can be done with the &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/#scale&#34;&gt;&lt;code&gt;scale()&lt;/code&gt;&lt;/a&gt; function.&lt;/p&gt;
&lt;p&gt;Now that the distance has been presented, let’s see how to perform clustering analysis with the k-means algorithm.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;k-means-clustering&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;&lt;em&gt;k&lt;/em&gt;-means clustering&lt;/h1&gt;
&lt;p&gt;The first form of classification is the method called &lt;em&gt;&lt;em&gt;k&lt;/em&gt;-means clustering&lt;/em&gt; or the mobile center algorithm. As a reminder, this method aims at partitioning &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; observations into &lt;span class=&#34;math inline&#34;&gt;\(k\)&lt;/span&gt; clusters in which each observation belongs to the cluster with the closest average, serving as a prototype of the cluster.&lt;/p&gt;
&lt;p&gt;We do not go too much into details about the mathematics. Instead, we focus on how to apply it in R and by hand.&lt;/p&gt;
&lt;div id=&#34;application-2-k-means-clustering&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Application 2: &lt;em&gt;k&lt;/em&gt;-means clustering&lt;/h2&gt;
&lt;div id=&#34;data&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Data&lt;/h3&gt;
&lt;p&gt;For this exercise, the &lt;code&gt;Eurojobs.csv&lt;/code&gt; database available &lt;a href=&#34;https://statsandr.com/blog/data/Eurojobs.csv&#34;&gt;here&lt;/a&gt; is used.&lt;/p&gt;
&lt;p&gt;This database contains the percentage of the population employed in different industries in 26 European countries in 1979. It contains 10 variables:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Country&lt;/code&gt; - the name of the country (identifier)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Agr&lt;/code&gt; - % of workforce employed in agriculture&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Min&lt;/code&gt; - % in mining&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Man&lt;/code&gt; - % in manufacturing&lt;/li&gt;
&lt;li&gt;&lt;code&gt;PS&lt;/code&gt; - % in power supplies industries&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Con&lt;/code&gt; - % in construction&lt;/li&gt;
&lt;li&gt;&lt;code&gt;SI&lt;/code&gt; - % in service industries&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Fin&lt;/code&gt; - % in finance&lt;/li&gt;
&lt;li&gt;&lt;code&gt;SPS&lt;/code&gt; - % in social and personal services&lt;/li&gt;
&lt;li&gt;&lt;code&gt;TC&lt;/code&gt; - % in transportation and communications&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We first import the dataset. See &lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/&#34;&gt;how to import data into R&lt;/a&gt; if you need a reminder.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Import data
Eurojobs &amp;lt;- read.csv(
  file = &amp;quot;https://statsandr.com/blog/data/Eurojobs.csv&amp;quot;,
  sep = &amp;quot;,&amp;quot;,
  dec = &amp;quot;.&amp;quot;,
  header = TRUE
)

head(Eurojobs) # head() is used to display only the first 6 observations&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      Country  Agr Min  Man  PS  Con   SI Fin  SPS  TC
## 1    Belgium  3.3 0.9 27.6 0.9  8.2 19.1 6.2 26.6 7.2
## 2    Denmark  9.2 0.1 21.8 0.6  8.3 14.6 6.5 32.2 7.1
## 3     France 10.8 0.8 27.5 0.9  8.9 16.8 6.0 22.6 5.7
## 4 W. Germany  6.7 1.3 35.8 0.9  7.3 14.4 5.0 22.3 6.1
## 5    Ireland 23.2 1.0 20.7 1.3  7.5 16.8 2.8 20.8 6.1
## 6      Italy 15.9 0.6 27.6 0.5 10.0 18.1 1.6 20.1 5.7&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that there is a numbering before the first variable &lt;code&gt;Country&lt;/code&gt;. For more clarity, we will replace this numbering by the country. To do this, we add the argument &lt;code&gt;row.names = 1&lt;/code&gt; in the import function &lt;code&gt;read.csv()&lt;/code&gt; to specify that the first column corresponds to the row names:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;Eurojobs &amp;lt;- read.csv(
  file = &amp;quot;https://statsandr.com/blog/data/Eurojobs.csv&amp;quot;,
  sep = &amp;quot;,&amp;quot;,
  dec = &amp;quot;.&amp;quot;,
  header = TRUE,
  row.names = 1
)

Eurojobs # displays dataset&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##                 Agr Min  Man  PS  Con   SI  Fin  SPS  TC
## Belgium         3.3 0.9 27.6 0.9  8.2 19.1  6.2 26.6 7.2
## Denmark         9.2 0.1 21.8 0.6  8.3 14.6  6.5 32.2 7.1
## France         10.8 0.8 27.5 0.9  8.9 16.8  6.0 22.6 5.7
## W. Germany      6.7 1.3 35.8 0.9  7.3 14.4  5.0 22.3 6.1
## Ireland        23.2 1.0 20.7 1.3  7.5 16.8  2.8 20.8 6.1
## Italy          15.9 0.6 27.6 0.5 10.0 18.1  1.6 20.1 5.7
## Luxembourg      7.7 3.1 30.8 0.8  9.2 18.5  4.6 19.2 6.2
## Netherlands     6.3 0.1 22.5 1.0  9.9 18.0  6.8 28.5 6.8
## United Kingdom  2.7 1.4 30.2 1.4  6.9 16.9  5.7 28.3 6.4
## Austria        12.7 1.1 30.2 1.4  9.0 16.8  4.9 16.8 7.0
## Finland        13.0 0.4 25.9 1.3  7.4 14.7  5.5 24.3 7.6
## Greece         41.4 0.6 17.6 0.6  8.1 11.5  2.4 11.0 6.7
## Norway          9.0 0.5 22.4 0.8  8.6 16.9  4.7 27.6 9.4
## Portugal       27.8 0.3 24.5 0.6  8.4 13.3  2.7 16.7 5.7
## Spain          22.9 0.8 28.5 0.7 11.5  9.7  8.5 11.8 5.5
## Sweden          6.1 0.4 25.9 0.8  7.2 14.4  6.0 32.4 6.8
## Switzerland     7.7 0.2 37.8 0.8  9.5 17.5  5.3 15.4 5.7
## Turkey         66.8 0.7  7.9 0.1  2.8  5.2  1.1 11.9 3.2
## Bulgaria       23.6 1.9 32.3 0.6  7.9  8.0  0.7 18.2 6.7
## Czechoslovakia 16.5 2.9 35.5 1.2  8.7  9.2  0.9 17.9 7.0
## E. Germany      4.2 2.9 41.2 1.3  7.6 11.2  1.2 22.1 8.4
## Hungary        21.7 3.1 29.6 1.9  8.2  9.4  0.9 17.2 8.0
## Poland         31.1 2.5 25.7 0.9  8.4  7.5  0.9 16.1 6.9
## Rumania        34.7 2.1 30.1 0.6  8.7  5.9  1.3 11.7 5.0
## USSR           23.7 1.4 25.8 0.6  9.2  6.1  0.5 23.6 9.3
## Yugoslavia     48.7 1.5 16.8 1.1  4.9  6.4 11.3  5.3 4.0&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dim(Eurojobs) # displays the number of rows and columns&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 26  9&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We now have a “clean” dataset of 26 observations and 9 &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#continuous&#34;&gt;quantitative continuous variables&lt;/a&gt; on which we can base the classification. Note that in this case it is not necessary to standardize the data because they are all expressed in the same unit (in percentage). If this was not the case, we would have had to standardize the data via the &lt;code&gt;scale()&lt;/code&gt; function (do not forget it otherwise your results may be completely different!).&lt;/p&gt;
&lt;p&gt;The so-called &lt;em&gt;k&lt;/em&gt;-means clustering is done via the &lt;code&gt;kmeans()&lt;/code&gt; function, with the argument &lt;code&gt;centers&lt;/code&gt; that corresponds to the number of desired clusters. In the following we apply the classification with 2 classes and then 3 classes as examples.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;kmeans-with-2-groups&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;&lt;code&gt;kmeans()&lt;/code&gt; with 2 groups&lt;/h3&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;model &amp;lt;- kmeans(Eurojobs, centers = 2)

# displays the class determined by
# the model for all observations:
model$cluster&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##        Belgium        Denmark         France     W. Germany        Ireland 
##              1              1              1              1              2 
##          Italy     Luxembourg    Netherlands United Kingdom        Austria 
##              1              1              1              1              1 
##        Finland         Greece         Norway       Portugal          Spain 
##              1              2              1              2              2 
##         Sweden    Switzerland         Turkey       Bulgaria Czechoslovakia 
##              1              1              2              2              1 
##     E. Germany        Hungary         Poland        Rumania           USSR 
##              1              2              2              2              2 
##     Yugoslavia 
##              2&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the argument &lt;code&gt;centers = 2&lt;/code&gt; is used to set the number of clusters, determined in advance. In this exercise the number of clusters has been determined arbitrarily.&lt;/p&gt;
&lt;p&gt;This number of clusters should be determined according to the context and goal of your analysis (so according to your expectations or hypotheses), or based on methods explained in this &lt;a href=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r/#optimal-number-of-clusters&#34;&gt;section&lt;/a&gt;. The output &lt;code&gt;model$cluster&lt;/code&gt; specifies the group (i.e., 1 or 2) to which each country belongs to.&lt;/p&gt;
&lt;p&gt;The cluster for each observation can be stored directly in the dataset as a column:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;Eurojobs_cluster &amp;lt;- data.frame(Eurojobs,
  cluster = as.factor(model$cluster)
)

head(Eurojobs_cluster)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             Agr Min  Man  PS  Con   SI Fin  SPS  TC cluster
## Belgium     3.3 0.9 27.6 0.9  8.2 19.1 6.2 26.6 7.2       1
## Denmark     9.2 0.1 21.8 0.6  8.3 14.6 6.5 32.2 7.1       1
## France     10.8 0.8 27.5 0.9  8.9 16.8 6.0 22.6 5.7       1
## W. Germany  6.7 1.3 35.8 0.9  7.3 14.4 5.0 22.3 6.1       1
## Ireland    23.2 1.0 20.7 1.3  7.5 16.8 2.8 20.8 6.1       2
## Italy      15.9 0.6 27.6 0.5 10.0 18.1 1.6 20.1 5.7       1&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;quality-of-a-k-means-partition&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Quality of a &lt;em&gt;k&lt;/em&gt;-means partition&lt;/h3&gt;
&lt;p&gt;The quality of a &lt;em&gt;k&lt;/em&gt;-means partition is found by calculating the percentage of the &lt;em&gt;TSS&lt;/em&gt; “explained” by the partition using the following formula:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{equation}
\dfrac{\operatorname{BSS}}{\operatorname{TSS}} \times 100\%
\end{equation}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;em&gt;BSS&lt;/em&gt; and &lt;em&gt;TSS&lt;/em&gt; stand for &lt;em&gt;Between Sum of Squares&lt;/em&gt; and &lt;em&gt;Total Sum of Squares&lt;/em&gt;, respectively. The higher the percentage, the better the score (and thus the quality) because it means that &lt;em&gt;BSS&lt;/em&gt; is large and/or &lt;em&gt;WSS&lt;/em&gt; is small.&lt;/p&gt;
&lt;p&gt;Here is how you can check the quality of the partition in R:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# BSS and TSS are extracted from the model and stored
(BSS &amp;lt;- model$betweenss)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 4823.535&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;(TSS &amp;lt;- model$totss)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 9299.59&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# We calculate the quality of the partition
BSS / TSS * 100&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 51.86826&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The quality of the partition is 51.87%. This value has no real interpretation in absolute terms except that a higher quality means a higher explained percentage. However, it is more insightful when it is compared to the quality of other partitions (with the same number of clusters! see why at the end of this &lt;a href=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r/#kmeans-with-3-groups&#34;&gt;section&lt;/a&gt;) in order to determine the best partition among the ones considered.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;nstart-for-several-initial-centers-and-better-stability&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;&lt;code&gt;nstart&lt;/code&gt; for several initial centers and better stability&lt;/h3&gt;
&lt;p&gt;Note that &lt;em&gt;k&lt;/em&gt;-means is a non-deterministic algorithm so running it multiple times may result in different classification. This is the case because the &lt;em&gt;k&lt;/em&gt;-means algorithm uses a &lt;strong&gt;random&lt;/strong&gt; set of initial points to arrive at the final classification. Due to the fact that the initial centers are randomly chosen, the same command &lt;code&gt;kmeans(Eurojobs, centers = 2)&lt;/code&gt; may give different results every time it is run, and thus slight differences in the quality of the partitions. The &lt;code&gt;nstart&lt;/code&gt; argument in the &lt;code&gt;kmeans()&lt;/code&gt; function allows to run the algorithm several times with different initial centers, in order to obtain a potentially better partition:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;model2 &amp;lt;- kmeans(Eurojobs, centers = 2, nstart = 10)
100 * model2$betweenss / model2$totss&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 54.2503&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Depending on the initial random choices, this new partition will be better or not compared to the first one. In our example, the partition is better as the quality increased to 54.25%.&lt;/p&gt;
&lt;p&gt;One of the main limitation often cited regarding &lt;em&gt;k&lt;/em&gt;-means is the stability of the results. As the initial centers are randomly chosen, running the same command may yield different results. Adding the &lt;code&gt;nstart&lt;/code&gt; argument in the &lt;code&gt;kmeans()&lt;/code&gt; function limits this issue as it will generate several different initializations and take the most optimal one, leading to a better stability of the classification.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;kmeans-with-3-groups&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;&lt;code&gt;kmeans()&lt;/code&gt; with 3 groups&lt;/h3&gt;
&lt;p&gt;We now perform the &lt;em&gt;k&lt;/em&gt;-means classification with 3 clusters and compute its quality:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;model3 &amp;lt;- kmeans(Eurojobs, centers = 3)

BSS3 &amp;lt;- model3$betweenss
TSS3 &amp;lt;- model3$totss
BSS3 / TSS3 * 100&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 74.59455&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It can be seen that the classification into three groups allows for a higher explained percentage and a higher quality.&lt;/p&gt;
&lt;p&gt;This will always be the case: with more classes, the partition will be finer, and the &lt;em&gt;BSS&lt;/em&gt; contribution will be higher. On the other hand, the “model” will be more complex, requiring more classes. In the extreme case where &lt;em&gt;k = n&lt;/em&gt; (each observation is a singleton class), we have &lt;em&gt;BSS = TSS&lt;/em&gt;, but the partition has lost all interest.&lt;/p&gt;
&lt;p&gt;This is the reason we compare partitions via their quality only for partitions that have the same number of clusters.&lt;/p&gt;
&lt;p&gt;An alternative method to perform a &lt;em&gt;k&lt;/em&gt;-means is to use the &lt;code&gt;cluster_analysis()&lt;/code&gt; function from the &lt;code&gt;{parameters}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(parameters)

res_kmeans &amp;lt;- cluster_analysis(Eurojobs,
  n = 3,
  method = &amp;quot;kmeans&amp;quot;
)

predict(res_kmeans) # get clusters&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1] 2 2 2 2 2 2 2 2 2 2 2 3 2 2 2 2 2 1 3 3 3 3 3 3 3 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;An advantage of this method is that it is possible to visualize the centers (i.e., the average of each variable for each cluster):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(summary(res_kmeans))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-14-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;optimal-number-of-clusters&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Optimal number of clusters&lt;/h3&gt;
&lt;p&gt;In order to find the optimal number of clusters for a &lt;em&gt;k&lt;/em&gt;-means, it is recommended to choose it based on:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the context of the problem at hand, for instance if you know that there is a specific number of groups in your data (you have strong expectations or hypotheses, this is option is however subjective), or&lt;/li&gt;
&lt;li&gt;the following four approaches:
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Elbow method (which uses the within cluster sums of squares)&lt;/li&gt;
&lt;li&gt;Average silhouette method&lt;/li&gt;
&lt;li&gt;Gap statistic method&lt;/li&gt;
&lt;li&gt;Consensus-based algorithm&lt;/li&gt;
&lt;/ol&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We show the R code for these 4 methods below, more theoretical information can be found &lt;a href=&#34;https://www.datanovia.com/en/lessons/determining-the-optimal-number-of-clusters-3-must-know-methods/&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;div id=&#34;elbow-method&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Elbow method&lt;/h4&gt;
&lt;p&gt;The Elbow method looks at the total within-cluster sum of square (WSS) as a function of the number of clusters.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load required packages
library(factoextra)
library(NbClust)

# Elbow method
fviz_nbclust(Eurojobs, kmeans, method = &amp;quot;wss&amp;quot;) +
  geom_vline(xintercept = 4, linetype = 2) + # add line for better visualisation
  labs(subtitle = &amp;quot;Elbow method&amp;quot;) # add subtitle&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-15-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The location of a knee in the plot is usually considered as an indicator of the appropriate number of clusters because it means that adding another cluster does not improve much better the partition. This method seems to suggest 4 clusters.&lt;/p&gt;
&lt;p&gt;The Elbow method is sometimes ambiguous and an alternative is the average silhouette method.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;silhouette-method&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Silhouette method&lt;/h4&gt;
&lt;p&gt;The Silhouette method measures the quality of a clustering and determines how well each point lies within its cluster.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Silhouette method
fviz_nbclust(Eurojobs, kmeans, method = &amp;quot;silhouette&amp;quot;) +
  labs(subtitle = &amp;quot;Silhouette method&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-16-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The Silhouette method suggests 2 clusters.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;gap-statistic-method&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Gap statistic method&lt;/h4&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Gap statistic
set.seed(42)
fviz_nbclust(Eurojobs, kmeans,
  nstart = 25,
  method = &amp;quot;gap_stat&amp;quot;,
  nboot = 500 # reduce it for lower computation time (but less precise results)
) +
  labs(subtitle = &amp;quot;Gap statistic method&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-17-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The optimal number of clusters is the one that maximizes the gap statistic. This method suggests only 1 cluster (which is therefore a useless clustering).&lt;/p&gt;
&lt;p&gt;As you can see these three methods do not necessarily lead to the same result. Here, the 3 approaches suggest a different number of clusters.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;consensus-based-algorithm&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Consensus-based algorithm&lt;/h4&gt;
&lt;p&gt;Because no method is clearly better, a fourth alternative is to run many methods and take the number of clusters that is the most agreed upon (i.e., find the consensus).&lt;/p&gt;
&lt;p&gt;This can easily be done with the &lt;code&gt;n_clusters()&lt;/code&gt; function from the &lt;code&gt;{parameters}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(parameters)

n_clust &amp;lt;- n_clusters(Eurojobs,
  package = c(&amp;quot;easystats&amp;quot;, &amp;quot;NbClust&amp;quot;, &amp;quot;mclust&amp;quot;),
  standardize = FALSE
)
n_clust&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # Method Agreement Procedure:
## 
## The choice of 3 clusters is supported by 15 (51.72%) methods out of 29 (kl, Ch, Hartigan, CCC, Scott, Marriot, trcovw, Tracew, Rubin, Beale, Ratkowsky, Ball, PtBiserial, Dunn, SDindex).&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The optimal number of clusters to retain can also be visualized:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(n_clust)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-19-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Based on all indices, most methods suggest to retain 3 clusters.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;visualizations&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Visualizations&lt;/h3&gt;
&lt;p&gt;To confirm that your number of classes is indeed optimal, there is a way to evaluate the quality of your clustering via the silhouette plot (which shows the silhouette coefficient on the &lt;em&gt;y&lt;/em&gt; axis).&lt;/p&gt;
&lt;p&gt;We draw the silhouette plot for 2 clusters, as suggested by the average silhouette method:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(cluster)

set.seed(42)
km_res &amp;lt;- kmeans(Eurojobs, centers = 2, nstart = 20)

sil &amp;lt;- silhouette(km_res$cluster, dist(Eurojobs))
fviz_silhouette(sil)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   cluster size ave.sil.width
## 1       1    5          0.33
## 2       2   21          0.54&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-20-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;As a reminder, the interpretation of the silhouette coefficient is as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(&amp;gt; 0\)&lt;/span&gt; means that the observation is well grouped. The closer the coefficient is to 1, the better the observation is grouped.&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(&amp;lt; 0\)&lt;/span&gt; means that the observation has been placed in the wrong cluster.&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(= 0\)&lt;/span&gt; means that the observation is between two clusters.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The silhouette plot above and the average silhouette coefficient help to determine whether your clustering is good or not. If a large majority of the silhouette coefficients are positive, it indicates that the observations are placed in the correct group. This silhouette plot can therefore be used in the choice of the optimal number of classes.&lt;/p&gt;
&lt;p&gt;It is also possible to plot clusters by using the &lt;code&gt;fviz_cluster()&lt;/code&gt; function. Note that a principal component analysis is performed to represent the variables in a 2 dimensions plane.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(factoextra)

fviz_cluster(km_res, Eurojobs, ellipse.type = &amp;quot;norm&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-21-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Now that the &lt;em&gt;k&lt;/em&gt;-means clustering has been detailed in R, see how to do the algorithm by hand in the following sections.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;manual-application-and-verification-in-r&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Manual application and verification in R&lt;/h3&gt;
&lt;p&gt;Perform &lt;strong&gt;by hand&lt;/strong&gt; the &lt;em&gt;k&lt;/em&gt;-means algorithm for the points shown in the graph below, with &lt;em&gt;k&lt;/em&gt; = 2 and with the points &lt;em&gt;i&lt;/em&gt; = 5 and &lt;em&gt;i&lt;/em&gt; = 6 as initial centers. Compute the quality of the partition you just found and then &lt;strong&gt;check&lt;/strong&gt; your answers &lt;strong&gt;in R&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Assume that the variables have the same units so there is no need to scale the data.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-22-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;solution-by-hand&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Solution by hand&lt;/h4&gt;
&lt;p&gt;Step 1. Here are the coordinates of the 6 points:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-cly1{text-align:left;vertical-align:middle}
.tg .tg-0lax{text-align:left;vertical-align:top}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
point
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
x
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
y
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
7
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
3
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
4
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
5
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
3
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
2
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
4
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
4
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
1
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
5
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
9
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
7
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
6
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
6
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
8
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;And the initial centers:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Group 1: point 5 with center &lt;em&gt;(9, 7)&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;Group 2: point 6 with center &lt;em&gt;(6, 8)&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Step 2. Compute the distance matrix point by point with the Pythagorean theorem. Remind that the distance between point &lt;em&gt;a&lt;/em&gt; and point &lt;em&gt;b&lt;/em&gt; is found with:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\sqrt{(x_a - x_b)^2 + (y_a - y_b)^2}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;We apply this theorem to each pair of points, to finally have the following distance matrix (rounded to two decimals):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;round(dist(X), 2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       1     2     3     4     5
## 2  3.61                        
## 3  5.10  2.24                  
## 4  7.28  5.66  3.61            
## 5  4.47  5.39  7.62 10.82      
## 6  5.10  3.61  5.66  9.22  3.16&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Step 3. Based on the distance matrix computed in step 2, we can put each point to its closest group and compute the coordinates of the center.&lt;/p&gt;
&lt;p&gt;We first put each point in its closest group:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;point 1 is closer to point 5 than to point 6 because the distance between points 1 and 5 is 4.47 while the distance between points 1 and 6 is 5.10&lt;/li&gt;
&lt;li&gt;point 2 is closer to point 6 than to point 5 because the distance between points 2 and 5 is 5.39 while the distance between points 2 and 6 is 3.61&lt;/li&gt;
&lt;li&gt;point 3 is closer to point 6 than to point 5 because the distance between points 3 and 5 is 7.62 while the distance between points 3 and 6 is 5.66&lt;/li&gt;
&lt;li&gt;point 4 is closer to point 6 than to point 5 because the distance between points 4 and 5 is 10.82 while the distance between points 4 and 6 is 9.22&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that computing the distances between each point and the points 5 and 6 is sufficient. There is no need to compute the distance between the points 1 and 2 for example, as we compare each point to the initial centers (which are points 5 and 6).&lt;/p&gt;
&lt;p&gt;We then compute the coordinates of the centers of the two groups by taking the mean of the coordinates &lt;em&gt;x&lt;/em&gt; and &lt;em&gt;y&lt;/em&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Group 1 includes the points 5 and 1 with &lt;em&gt;(8, 5)&lt;/em&gt; as center (&lt;span class=&#34;math inline&#34;&gt;\(8 = \frac{9+7}{2}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(5 = \frac{7+3}{2}\)&lt;/span&gt;)&lt;/li&gt;
&lt;li&gt;Group 2 includes the points 6, 2, 3 and 4 with &lt;em&gt;(3, 4.5)&lt;/em&gt; as center (&lt;span class=&#34;math inline&#34;&gt;\(3 = \frac{6+4+2+0}{4}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(4.5 = \frac{8+5+4+1}{4}\)&lt;/span&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We thus have:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-cly1{text-align:left;vertical-align:middle}
.tg .tg-0lax{text-align:left;vertical-align:top}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
points
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
center
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
cluster 1
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
5 &amp;amp; 1
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
(8, 5)
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
cluster 2
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
6, 2, 3 &amp;amp; 4
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
(3, 4.5)
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Step 4. We make sure that the allocation is optimal by checking that each point is in the nearest cluster. The distance between a point and the center of a cluster is again computed thanks to the Pythagorean theorem. Thus, we have:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-cly1{text-align:left;vertical-align:middle}
.tg .tg-scde{color:#009901;text-align:left;vertical-align:middle}
.tg .tg-0lax{text-align:left;vertical-align:top}
.tg .tg-yi9q{color:#009901;text-align:left;vertical-align:top}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
points
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
Distance to cluster 1
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
Distance to cluster 2
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1
&lt;/td&gt;
&lt;td class=&#34;tg-scde&#34;&gt;
2.24
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
4.27
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
4
&lt;/td&gt;
&lt;td class=&#34;tg-scde&#34;&gt;
1.12
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
3
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
6.08
&lt;/td&gt;
&lt;td class=&#34;tg-yi9q&#34;&gt;
1.12
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
4
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
8.94
&lt;/td&gt;
&lt;td class=&#34;tg-yi9q&#34;&gt;
4.61
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
5
&lt;/td&gt;
&lt;td class=&#34;tg-yi9q&#34;&gt;
2.24
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
6.5
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
6
&lt;/td&gt;
&lt;td class=&#34;tg-yi9q&#34;&gt;
3.61
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
4.61
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The minimum distance between the points and the two clusters is colored in green.&lt;/p&gt;
&lt;p&gt;We check that each point is in the correct group (i.e., the closest cluster). According to the distance in the table above, point 6 seems to be closer to the cluster 1 than to the cluster 2. Therefore, the allocation is not optimal and point 6 should be reallocated to cluster 1.&lt;/p&gt;
&lt;p&gt;Step 5. We compute again the centers of the clusters after this reallocation. The centers are found by taking the mean of the coordinates &lt;em&gt;x&lt;/em&gt; and &lt;em&gt;y&lt;/em&gt; of the points belonging to the cluster. We thus have:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-cly1{text-align:left;vertical-align:middle}
.tg .tg-0lax{text-align:left;vertical-align:top}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
points
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
center
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
cluster 1
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1, 5 &amp;amp; 6
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
(7.33, 6)
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
cluster 2
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
2, 3 &amp;amp; 4
&lt;/td&gt;
&lt;td class=&#34;tg-0lax&#34;&gt;
(2, 3.33)
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;where, for instance, 3.33 is simply &lt;span class=&#34;math inline&#34;&gt;\(\frac{5+4+1}{3}\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Step 6. Repeat step 4 until the allocation is optimal. If the allocation is optimal, the algorithm stops. In our example we have:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-cly1{text-align:left;vertical-align:middle}
.tg .tg-scde{color:#009901;text-align:left;vertical-align:middle}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
points
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
Distance to cluster 1
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
Distance to cluster 2
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1
&lt;/td&gt;
&lt;td class=&#34;tg-scde&#34;&gt;
3.02
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
5.01
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
3.48
&lt;/td&gt;
&lt;td class=&#34;tg-scde&#34;&gt;
2.61
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
3
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
5.69
&lt;/td&gt;
&lt;td class=&#34;tg-scde&#34;&gt;
0.67
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
4
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
8.87
&lt;/td&gt;
&lt;td class=&#34;tg-scde&#34;&gt;
3.07
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
5
&lt;/td&gt;
&lt;td class=&#34;tg-scde&#34;&gt;
1.95
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
7.9
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
6
&lt;/td&gt;
&lt;td class=&#34;tg-scde&#34;&gt;
2.4
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
6.15
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;All points are correctly allocated to its nearest cluster, so the allocation is optimal and the algorithm stops.&lt;/p&gt;
&lt;p&gt;Step 7. State the final partition and the centers. In our example:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-cly1{text-align:left;vertical-align:middle}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
points
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
center
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
cluster 1
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1, 5 &amp;amp; 6
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
(7.33, 6)
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
cluster 2
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2, 3 &amp;amp; 4
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
(2, 3.33)
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Now that we have the clusters and the final centers, we compute the quality of the partition we just found. Remember that we need to compute the BSS and TSS to find the quality. Below the steps to compute the quality of this partition by &lt;em&gt;k&lt;/em&gt;-means, based on this summary table:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-cly1{text-align:left;vertical-align:middle}
.tg .tg-0lax{text-align:left;vertical-align:top}
.tg .tg-0a7q{border-color:#000000;text-align:left;vertical-align:middle}
.tg .tg-73oq{border-color:#000000;text-align:left;vertical-align:top}
&lt;/style&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-0pky{border-color:inherit;text-align:left;vertical-align:top}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-0pky&#34; colspan=&#34;3&#34;&gt;
cluster 1
&lt;/th&gt;
&lt;th class=&#34;tg-0pky&#34; colspan=&#34;3&#34;&gt;
cluster 2
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
point
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
x
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
y
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
point
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
x
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
y
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
1
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
7
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
3
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
2
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
4
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
5
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
5
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
9
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
7
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
3
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
2
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
4
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
6
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
6
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
8
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
4
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
1
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
mean
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
7.33
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
6
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
2
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
3.33
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Step 1. Compute the overall mean of the &lt;em&gt;x&lt;/em&gt; and &lt;em&gt;y&lt;/em&gt; coordinates:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\overline{\overline{x}} = \frac{7+4+2+0+9+6}{12} \\
\frac{+3+5+4+1+7+8}{12} \\ = 4.67\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Step 2. Compute TSS and WSS:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[TSS = (7-4.67)^2 + (4-4.67)^2 + (2-4.67)^2 \\ + (0-4.67)^2 + (9-4.67)^2 + (6-4.67)^2 \\ + (3-4.67)^2 + (5-4.67)^2 + (4-4.67)^2 \\ + (1-4.67)^2 + (7-4.67)^2 + (8-4.67)^2 \\ = 88.67\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Regarding WSS, it is splitted between cluster 1 and cluster 2. For cluster 1:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[WSS[1] = (7-7.33)^2 + (9 - 7.33)^2 \\ + (6 - 7.33)^2 + (3-6)^2 \\ + (7-6)^2 + (8-6)^2 \\ = 18.67\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For cluster 2:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[WSS[2] = (4-2)^2 + (2-2)^2 + (0-2)^2 \\ + (5-3.33)^2 + (4-3.33)^2 + (1-3.33)^2 \\ = 16.67\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;And the total WSS is&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
WSS &amp;amp;= WSS[1] + WSS[2] \\
&amp;amp;= 18.67 + 16.67 \\
&amp;amp;= 35.34
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;To find the BSS:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
BSS &amp;amp;= TSS - WSS \\
&amp;amp;= 88.67 - 35.34 \\
&amp;amp;= 53.33
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Finally, the quality of the partition is:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[Quality = \frac{BSS}{TSS} = \frac{53.33}{88.67} = 0.6014\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;So the quality of the partition is 60.14%.&lt;/p&gt;
&lt;p&gt;We are now going to verify all these solutions (the partition, the final centers and the quality) in R.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;solution-in-r&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Solution in R&lt;/h4&gt;
&lt;p&gt;As you can imagine, the solution in R us much shorter and requires much less computation on the user side. We first need to enter the data as a matrix or dataframe:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;X &amp;lt;- matrix(c(7, 3, 4, 5, 2, 4, 0, 1, 9, 7, 6, 8),
  nrow = 6, byrow = TRUE
)
X # display the coordinates of the points&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      [,1] [,2]
## [1,]    7    3
## [2,]    4    5
## [3,]    2    4
## [4,]    0    1
## [5,]    9    7
## [6,]    6    8&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We now perform the &lt;em&gt;k&lt;/em&gt;-means via the &lt;code&gt;kmeans()&lt;/code&gt; function with the point 5 and 6 as initial centers:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# take rows 5 and 6 of the X matrix as initial centers
res.k &amp;lt;- kmeans(X,
  centers = X[c(5, 6), ],
  algorithm = &amp;quot;Lloyd&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Unlike in the previous application with the dataset &lt;code&gt;Eurojobs.csv&lt;/code&gt; where the initial centers are randomly chosen by R, in this second application we want to specify which points are going to be the two initial centers. For this, we need to set &lt;code&gt;centers = X[c(5,6), ]&lt;/code&gt; to indicate that that there are 2 centers, and that they are going to be the points 5 and 6 (see a reminder on &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/&#34;&gt;how to subset a dataframe&lt;/a&gt; if needed).&lt;/p&gt;
&lt;p&gt;The reason for adding the argument &lt;code&gt;algorithm = &#34;Lloyd&#34;&lt;/code&gt; can be found in the usage of the R function &lt;code&gt;kmeans()&lt;/code&gt;. In fact, there are several variants of the &lt;em&gt;k&lt;/em&gt;-means algorithm. The default choice is the &lt;span class=&#34;citation&#34;&gt;Hartigan and Wong (&lt;a href=&#34;#ref-jaaw28m&#34;&gt;1979&lt;/a&gt;)&lt;/span&gt; version, which is more sophisticated than the basic version detailed in the solution by hand. By using the original version of &lt;span class=&#34;citation&#34;&gt;Lloyd (&lt;a href=&#34;#ref-lloyd1982least&#34;&gt;1982&lt;/a&gt;)&lt;/span&gt;, we find the same solution in R and by hand. For more information, you can consult the documentation of the &lt;code&gt;kmeans()&lt;/code&gt; function (via &lt;code&gt;?kmeans&lt;/code&gt; or &lt;code&gt;help(kmeans)&lt;/code&gt;) and read the articles mentioned.&lt;/p&gt;
&lt;p&gt;The solution in R is then found by extracting&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the partition with &lt;code&gt;$cluster&lt;/code&gt;:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;res.k$cluster&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1 2 2 2 1 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Points 1, 5 and 6 belong to cluster 1, points 2, 3 and 4 belong to cluster 2.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the coordinates of the final centers with &lt;code&gt;$centers&lt;/code&gt;:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# We extract the coordinates of the 2 final centers, rounded to 2 decimals
round(res.k$centers, digits = 2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   [,1] [,2]
## 1 7.33 6.00
## 2 2.00 3.33&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;and then the quality of the partition by dividing the BSS to the TSS:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;res.k$betweenss / res.k$totss&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.6015038&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The 3 results are equal to what we found by hand (except the quality which is slightly different due to rounding).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;hierarchical-clustering&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Hierarchical clustering&lt;/h1&gt;
&lt;p&gt;Remind that the difference with the partition by &lt;em&gt;k&lt;/em&gt;-means is that for hierarchical clustering, the number of classes is &lt;strong&gt;not&lt;/strong&gt; specified in advance. Hierarchical clustering will help to determine the optimal number of clusters.&lt;/p&gt;
&lt;p&gt;Before applying hierarchical clustering by hand and in R, let’s see how the ascending hierarchical clustering works step by step:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;It starts by putting every point in its own cluster, so each cluster is a singleton&lt;/li&gt;
&lt;li&gt;It then merges the 2 points that are closest to each other based on the distances from the distance matrix. The consequence is that there is one less cluster&lt;/li&gt;
&lt;li&gt;It then recalculates the distances between the new and old clusters and save them in a new distance matrix which will be used in the next step&lt;/li&gt;
&lt;li&gt;Finally, steps 1 and 2 are repeated until all clusters are merged into one single cluster including all points.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;There are 5 main methods to measure the distance between clusters, referred as linkage methods:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Single linkage: computes the minimum distance between clusters before merging them.&lt;/li&gt;
&lt;li&gt;Complete linkage: computes the maximum distance between clusters before merging them.&lt;/li&gt;
&lt;li&gt;Average linkage: computes the average distance between clusters before merging them.&lt;/li&gt;
&lt;li&gt;Centroid linkage: calculates centroids for both clusters, then computes the distance between the two before merging them.&lt;/li&gt;
&lt;li&gt;Ward’s (minimum variance) criterion: minimizes the total within-cluster variance and find the pair of clusters that leads to minimum increase in total within-cluster variance after merging.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In the following sections, only the three first linkage methods are presented (first by hand and then the results are verified in R).&lt;/p&gt;
&lt;div id=&#34;application-3-hierarchical-clustering&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Application 3: hierarchical clustering&lt;/h2&gt;
&lt;div id=&#34;data-1&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Data&lt;/h3&gt;
&lt;p&gt;Using the data from the graph and the table below, we perform &lt;strong&gt;by hand&lt;/strong&gt; the 3 algorithms (single, complete and average linkage) and we draw the dendrograms. Then we &lt;strong&gt;check&lt;/strong&gt; our answers &lt;strong&gt;in R&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-29-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;##      V1    V2
## 1  2.03  0.06
## 2 -0.64 -0.10
## 3 -0.42 -0.53
## 4 -0.36  0.07
## 5  1.14  0.37&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;We assume that the variables have the same units so there is no need to scale the data.&lt;/em&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;solution-by-hand-1&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Solution by hand&lt;/h3&gt;
&lt;p&gt;Step 1. For all 3 algorithms, we first need to compute the distance matrix between the 5 points thanks to the Pythagorean theorem. Remind that the distance between point &lt;em&gt;a&lt;/em&gt; and point &lt;em&gt;b&lt;/em&gt; is found with:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\sqrt{(x_a - x_b)^2 + (y_a - y_b)^2}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;We apply this theorem to each pair of points, to finally have the following distance matrix (rounded to three decimals):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;##       1     2     3     4
## 2 2.675                  
## 3 2.520 0.483            
## 4 2.390 0.328 0.603      
## 5 0.942 1.841 1.801 1.530&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;single-linkage&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Single linkage&lt;/h4&gt;
&lt;p&gt;Step 2. From the distance matrix computed in step 1, we see that the &lt;strong&gt;smallest distance&lt;/strong&gt; = 0.328 between points 2 and 4. 0.328 corresponds to the first height (more on this later when drawing the dendrogram). Since points 2 and 4 are the closest to each other, these 2 points are put together to form a single group. The groups are thus: 1, 2 &amp;amp; 4, 3 and 5. The new distances between the group 2 &amp;amp; 4 and all other points are now:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-0pky{border-color:inherit;text-align:left;vertical-align:top}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
&lt;/th&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
1
&lt;/th&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
2 &amp;amp; 4
&lt;/th&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
3
&lt;/th&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
5
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
1
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
2 &amp;amp; 4
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
2.390
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
3
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
2.520
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0.483
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
5
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0.942
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
1.530
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
1.801
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;To construct this new distance matrix, proceed point by point:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the distance between points 1 and 3 has not changed, so the distance is unchanged compared to the initial distance matrix (found in step 1), which was 2.520&lt;/li&gt;
&lt;li&gt;same goes for the distance between points 1 and 5 and points 3 and 5; the distances are the same than in the initial distance matrix since the points have not changed&lt;/li&gt;
&lt;li&gt;the distance between points 1 and 2 &amp;amp; 4 has changed since points 2 &amp;amp; 4 are now together&lt;/li&gt;
&lt;li&gt;since we are applying the &lt;strong&gt;single linkage&lt;/strong&gt; criterion, the new distance between points 1 and 2 &amp;amp; 4 corresponds to the &lt;strong&gt;minimum distance&lt;/strong&gt; between the distance between points 1 and 2 and the distance between points 1 and 4&lt;/li&gt;
&lt;li&gt;the initial distance between points 1 and 2 is 2.675 and the initial distance between points 1 and 4 is 2.390&lt;/li&gt;
&lt;li&gt;therefore, the minimum distance between these two distances is 2.390&lt;/li&gt;
&lt;li&gt;2.390 is thus the new distance between points 1 and 2 &amp;amp; 4&lt;/li&gt;
&lt;li&gt;we apply the same process for points 3 and 2 &amp;amp; 4: the initial distance between points 3 and 2 is 0.483 and the initial distance between points 3 and 4 is 0.603. The minimum distance between these 2 distances is 0.483 so the new distance between points 3 and 2 &amp;amp; 4 is 0.483&lt;/li&gt;
&lt;li&gt;follow the same process for all other points&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Step 3. Based on the distance matrix in step 2, the smallest distance is 0.483 between points 3 and 2 &amp;amp; 4 (the second height for the dendrogram). Since points 3 and 2 &amp;amp; 4 are the closest to each other, they are combined to form a new group, the group 2 &amp;amp; 3 &amp;amp; 4. The groups are thus: 1, 2 &amp;amp; 3 &amp;amp; 4 and 5. We construct the new distance matrix based on the same process detailed in step 2:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-cly1{text-align:left;vertical-align:middle}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
1
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
2 &amp;amp; 3 &amp;amp; 4
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
5
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2 &amp;amp; 3 &amp;amp; 4
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2.390
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
5
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0.942
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1.530
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;points 1 and 5 have not change, so the distance between these two points are the same than in previous step&lt;/li&gt;
&lt;li&gt;from step 2 we see that the distance between points 1 and 2 &amp;amp; 4 is 2.390 and the distance between points 1 and 3 is 2.520&lt;/li&gt;
&lt;li&gt;since we apply the single linkage criterion, we take the minimum distance, which is 2.390&lt;/li&gt;
&lt;li&gt;the distance between points 1 and 2 &amp;amp; 3 &amp;amp; 4 is thus 2.390&lt;/li&gt;
&lt;li&gt;same process for points 5 and 2 &amp;amp; 3 &amp;amp; 4&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Step 4. Based on the distance matrix in step 3, the smallest distance is 0.942 between points 1 and 5 (the third height in the dendrogram). Since points 1 and 5 are the closest to each other, they are combined to form a new group, the group 1 &amp;amp; 5. The groups are thus: 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4. We construct the new distance matrix based on the same process detailed in steps 2 and 3:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-cly1{text-align:left;vertical-align:middle}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
1 &amp;amp; 5
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
2 &amp;amp; 3 &amp;amp; 4
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1 &amp;amp; 5
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2 &amp;amp; 3 &amp;amp; 4
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1.530
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the only distance left to compute is the distance between points 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4&lt;/li&gt;
&lt;li&gt;from the previous step we see that the distance between points 1 and 2 &amp;amp; 3 &amp;amp; 4 is 2.390 and the distance between points 5 and 2 &amp;amp; 3 &amp;amp; 4 is 1.530&lt;/li&gt;
&lt;li&gt;since we apply the single linkage criterion, we take the minimum distance, which is 1.530&lt;/li&gt;
&lt;li&gt;the distance between points 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4 is thus 1.530&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Step 5. The final combination of points is the combination of points 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4, with a final height of 1.530. Heights are used to draw the dendrogram in the sixth and final step.&lt;/p&gt;
&lt;p&gt;Step 6. Draw the dendrogram thanks to the combination of points and heights found above. Remember that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the first combination of points was between points 2 and 4, with a height of 0.328&lt;/li&gt;
&lt;li&gt;the second combination was between points 3 and 2 &amp;amp; 4 with a height of 0.483&lt;/li&gt;
&lt;li&gt;the third combination was between points 1 and 5 with a height of 0.942&lt;/li&gt;
&lt;li&gt;the final combination was between points 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4 with a height of 1.530&lt;/li&gt;
&lt;li&gt;this is exactly what is illustrated in the following dendrogram:&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-31-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In hierarchical clustering, dendrograms are used to show the sequence of combinations of the clusters. The distances of merge between clusters, called heights, are illustrated on the y-axis.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;complete-linkage&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Complete linkage&lt;/h4&gt;
&lt;p&gt;Complete linkage is quite similar to single linkage, except that instead of taking the smallest distance when computing the new distance between points that have been grouped, the &lt;strong&gt;maximum distance&lt;/strong&gt; is taken.&lt;/p&gt;
&lt;p&gt;The steps to perform the hierarchical clustering with the complete linkage (maximum) are detailed below.&lt;/p&gt;
&lt;p&gt;Step 1. Step 1 is exactly the same than for single linkage, that is, we compute the distance matrix of the 5 points thanks to the Pythagorean theorem. This gives us the following distance matrix:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;##       1     2     3     4
## 2 2.675                  
## 3 2.520 0.483            
## 4 2.390 0.328 0.603      
## 5 0.942 1.841 1.801 1.530&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Step 2. From the distance matrix computed in step 1, we see that the &lt;strong&gt;smallest distance&lt;/strong&gt; = 0.328 between points 2 and 4. It is important to note that even if we apply the complete linkage, in the distance matrix the points are brought together based on the smallest distance. This is the case for all 3 algorithms. The difference between the 3 algorithms lies in how to compute the new distances between the new combination of points (the single linkage takes the minimum between the distances, the complete linkage takes the maximum distance and the average linkage takes the average distance). 0.328 corresponds to the first height (which will be used when drawing the dendrogram). Since points 2 and 4 are the closest to each other, these 2 points are put together to form a single group. The groups are thus: 1, 2 &amp;amp; 4, 3 and 5. The new distances between the group 2 &amp;amp; 4 and all other points are now:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-0pky{border-color:inherit;text-align:left;vertical-align:top}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
&lt;/th&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
1
&lt;/th&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
2 &amp;amp; 4
&lt;/th&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
3
&lt;/th&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
5
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
1
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
2 &amp;amp; 4
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
2.675
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
3
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
2.520
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0.603
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
5
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0.942
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
1.841
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
1.801
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;To construct this new distance matrix, proceed point by point as we did for single linkage:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the distance between points 1 and 3 has not changed, so the distance is unchanged compared to the initial distance matrix (found in step 1), which was 2.520&lt;/li&gt;
&lt;li&gt;same goes for the distance between points 1 and 5 and points 3 and 5; the distances are the same than in the initial distance matrix since the points have not changed&lt;/li&gt;
&lt;li&gt;the distance between points 1 and 2 &amp;amp; 4 has changed since points 2 &amp;amp; 4 are now together&lt;/li&gt;
&lt;li&gt;since we are applying the &lt;strong&gt;complete linkage&lt;/strong&gt; criterion, the new distance between points 1 and 2 &amp;amp; 4 corresponds to the &lt;strong&gt;maximum distance&lt;/strong&gt; between the distance between points 1 and 2 and the distance between points 1 and 4&lt;/li&gt;
&lt;li&gt;the initial distance between points 1 and 2 is 2.675 and the initial distance between points 1 and 4 is 2.390&lt;/li&gt;
&lt;li&gt;therefore, the maximum distance between these two distances is 2.675&lt;/li&gt;
&lt;li&gt;2.675 is thus the new distance between points 1 and 2 &amp;amp; 4&lt;/li&gt;
&lt;li&gt;we apply the same process for points 3 and 2 &amp;amp; 4: the initial distance between points 3 and 2 is 0.483 and the initial distance between points 3 and 4 is 0.603. The maximum distance between these 2 distances is 0.603 so the new distance between points 3 and 2 &amp;amp; 4 is 0.603&lt;/li&gt;
&lt;li&gt;follow the same process for all other points&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Step 3. Based on the distance matrix in step 2, the smallest distance is 0.603 between points 3 and 2 &amp;amp; 4 (the second height for the dendrogram). Since points 3 and 2 &amp;amp; 4 are the closest to each other, they are combined to form a new group, the group 2 &amp;amp; 3 &amp;amp; 4. The groups are thus: 1, 2 &amp;amp; 3 &amp;amp; 4 and 5. We construct the new distance matrix based on the same process detailed in step 2:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-cly1{text-align:left;vertical-align:middle}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
1
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
2 &amp;amp; 3 &amp;amp; 4
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
5
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2 &amp;amp; 3 &amp;amp; 4
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2.675
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
5
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0.942
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1.841
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;points 1 and 5 have not change, so the distance between these two points are the same than in previous step&lt;/li&gt;
&lt;li&gt;from step 2 we see that the distance between points 1 and 2 &amp;amp; 4 is 2.675 and the distance between points 1 and 3 is 2.520&lt;/li&gt;
&lt;li&gt;since we apply the complete linkage criterion, we take the maximum distance, which is 2.675&lt;/li&gt;
&lt;li&gt;the distance between points 1 and 2 &amp;amp; 3 &amp;amp; 4 is thus 2.675&lt;/li&gt;
&lt;li&gt;same process for points 5 and 2 &amp;amp; 3 &amp;amp; 4&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Step 4. Based on the distance matrix in step 3, the smallest distance is 0.942 between points 1 and 5 (the third height in the dendrogram). Since points 1 and 5 are the closest to each other, they are combined to form a new group, the group 1 &amp;amp; 5. The groups are thus: 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4. We construct the new distance matrix based on the same process detailed in steps 2 and 3:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-cly1{text-align:left;vertical-align:middle}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
1 &amp;amp; 5
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
2 &amp;amp; 3 &amp;amp; 4
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1 &amp;amp; 5
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2 &amp;amp; 3 &amp;amp; 4
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2.675
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the only distance left to compute is the distance between points 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4&lt;/li&gt;
&lt;li&gt;from the previous step we see that the distance between points 1 and 2 &amp;amp; 3 &amp;amp; 4 is 2.675 and the distance between points 5 and 2 &amp;amp; 3 &amp;amp; 4 is 1.841&lt;/li&gt;
&lt;li&gt;since we apply the complete linkage criterion, we take the maximum distance, which is 2.675&lt;/li&gt;
&lt;li&gt;the distance between points 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4 is thus 2.675&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Step 5. The final combination of points is the combination of points 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4, with a final height of 2.675. Heights are used to draw the dendrogram in the sixth and final step.&lt;/p&gt;
&lt;p&gt;Step 6. Draw the dendrogram thanks to the combination of points and heights found above. Remember that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the first combination of points was between points 2 and 4, with a height of 0.328&lt;/li&gt;
&lt;li&gt;the second combination was between points 3 and 2 &amp;amp; 4 with a height of 0.603&lt;/li&gt;
&lt;li&gt;the third combination was between points 1 and 5 with a height of 0.942&lt;/li&gt;
&lt;li&gt;the final combination was between points 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4 with a height of 2.675&lt;/li&gt;
&lt;li&gt;this is exactly what is illustrated in the following dendrogram:&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-33-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;average-linkage&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Average linkage&lt;/h4&gt;
&lt;p&gt;With the average linkage criterion, it is not the minimum nor the maximum distance that is taken when computing the new distance between points that have been grouped, but it is, as you guessed by now, the &lt;strong&gt;average distance&lt;/strong&gt; between the points.&lt;/p&gt;
&lt;p&gt;The steps to perform the hierarchical clustering with the average linkage are detailed below.&lt;/p&gt;
&lt;p&gt;Step 1. Step 1 is exactly the same than for single and complete linkage, that is, we compute the distance matrix of the 5 points thanks to the Pythagorean theorem. This gives us the following distance matrix:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;##       1     2     3     4
## 2 2.675                  
## 3 2.520 0.483            
## 4 2.390 0.328 0.603      
## 5 0.942 1.841 1.801 1.530&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Step 2. From the distance matrix computed in step 1, we see that the &lt;strong&gt;smallest distance&lt;/strong&gt; = 0.328 between points 2 and 4. It is important to note that even if we apply the average linkage, in the distance matrix the points are brought together based on the smallest distance. This is the case for all 3 algorithms. The difference between the 3 algorithms lies in how to compute the new distances between the new combination of points (the single linkage takes the minimum between the distances, the complete linkage takes the maximum distance and the average linkage takes the average distance). 0.328 corresponds to the first height (which will be used when drawing the dendrogram). Since points 2 and 4 are the closest to each other, these 2 points are put together to form a single group. The groups are thus: 1, 2 &amp;amp; 4, 3 and 5. The new distances between the group 2 &amp;amp; 4 and all other points are now:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-0pky{border-color:inherit;text-align:left;vertical-align:top}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
&lt;/th&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
1
&lt;/th&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
2 &amp;amp; 4
&lt;/th&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
3
&lt;/th&gt;
&lt;th class=&#34;tg-0pky&#34;&gt;
5
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
1
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
2 &amp;amp; 4
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
2.5325
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
3
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
2.520
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0.543
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
5
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0.942
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
1.6855
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
1.801
&lt;/td&gt;
&lt;td class=&#34;tg-0pky&#34;&gt;
0
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;To construct this new distance matrix, proceed point by point as we did for the two previous criteria:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the distance between points 1 and 3 has not changed, so the distance is unchanged compared to the initial distance matrix (found in step 1), which was 2.520&lt;/li&gt;
&lt;li&gt;same goes for the distance between points 1 and 5 and points 3 and 5; the distances are the same than in the initial distance matrix since the points have not changed&lt;/li&gt;
&lt;li&gt;the distance between points 1 and 2 &amp;amp; 4 has changed since points 2 &amp;amp; 4 are now together&lt;/li&gt;
&lt;li&gt;since we are applying the &lt;strong&gt;average linkage&lt;/strong&gt; criterion, the new distance between points 1 and 2 &amp;amp; 4 corresponds to the &lt;strong&gt;average distance&lt;/strong&gt; between the distance between points 1 and 2 and the distance between points 1 and 4&lt;/li&gt;
&lt;li&gt;the initial distance between points 1 and 2 is 2.675 and the initial distance between points 1 and 4 is 2.390&lt;/li&gt;
&lt;li&gt;therefore, the average distance between these two distances is &lt;span class=&#34;math inline&#34;&gt;\(\frac{2.675 + 2.390}{2} = 2.5325\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;2.5325 is thus the new distance between points 1 and 2 &amp;amp; 4&lt;/li&gt;
&lt;li&gt;we apply the same process for points 3 and 2 &amp;amp; 4: the initial distance between points 3 and 2 is 0.483 and the initial distance between points 3 and 4 is 0.603. The average distance between these 2 distances is 0.543 so the new distance between points 3 and 2 &amp;amp; 4 is 0.543&lt;/li&gt;
&lt;li&gt;follow the same process for all other points&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Step 3. Based on the distance matrix in step 2, the smallest distance is 0.543 between points 3 and 2 &amp;amp; 4 (the second height for the dendrogram). Since points 3 and 2 &amp;amp; 4 are the closest to each other, they are combined to form a new group, the group 2 &amp;amp; 3 &amp;amp; 4. The groups are thus: 1, 2 &amp;amp; 3 &amp;amp; 4 and 5. We construct the new distance matrix based on the same process detailed in step 2:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-cly1{text-align:left;vertical-align:middle}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
1
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
2 &amp;amp; 3 &amp;amp; 4
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
5
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2 &amp;amp; 3 &amp;amp; 4
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2.528333
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
5
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0.942
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1.724
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;points 1 and 5 have not change, so the distance between these two points are the same than in previous step&lt;/li&gt;
&lt;li&gt;from step 2 we see that the distance between points 1 and 2 &amp;amp; 4 is 2.5325 and the distance between points 1 and 3 is 2.520&lt;/li&gt;
&lt;li&gt;since we apply the average linkage criterion, we take the average distance&lt;/li&gt;
&lt;li&gt;however, we have to take into the consideration that there are 2 points in the group 2 &amp;amp; 4, while there is only one point in the group 3&lt;/li&gt;
&lt;li&gt;the average distance for the distance between 1 and 2 &amp;amp; 3 &amp;amp; 4 is thus: &lt;span class=&#34;math inline&#34;&gt;\(\frac{(2 \cdot 2.5325) + (1 \cdot 2.520)}{3} = 2.528333\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;same process for points 5 and 2 &amp;amp; 3 &amp;amp; 4: &lt;span class=&#34;math inline&#34;&gt;\(\frac{(2 \cdot 1.6855) + (1 \cdot 1.801)}{3} = 1.724\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Step 4. Based on the distance matrix in step 3, the smallest distance is 0.942 between points 1 and 5 (the third height in the dendrogram). Since points 1 and 5 are the closest to each other, they are combined to form a new group, the group 1 &amp;amp; 5. The groups are thus: 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4. We construct the new distance matrix based on the same process detailed in steps 2 and 3:&lt;/p&gt;
&lt;center&gt;
&lt;style type=&#34;text/css&#34;&gt;
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-cly1{text-align:left;vertical-align:middle}
&lt;/style&gt;
&lt;table class=&#34;tg&#34;&gt;
&lt;tr&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
1 &amp;amp; 5
&lt;/th&gt;
&lt;th class=&#34;tg-cly1&#34;&gt;
2 &amp;amp; 3 &amp;amp; 4
&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
1 &amp;amp; 5
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2 &amp;amp; 3 &amp;amp; 4
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
2.126167
&lt;/td&gt;
&lt;td class=&#34;tg-cly1&#34;&gt;
0
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the only distance left to compute is the distance between points 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4&lt;/li&gt;
&lt;li&gt;from the previous step we see that the distance between points 1 and 2 &amp;amp; 3 &amp;amp; 4 is 2.528333 and the distance between points 5 and 2 &amp;amp; 3 &amp;amp; 4 is 1.724&lt;/li&gt;
&lt;li&gt;since we apply the average linkage criterion, we take the average distance, which is &lt;span class=&#34;math inline&#34;&gt;\(\frac{2.528333 + 1.724}{2} = 2.126167\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;the distance between points 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4 is thus 2.126167&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Step 5. The final combination of points is the combination of points 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4, with a final height of 2.126167. Heights are used to draw the dendrogram in the sixth and final step.&lt;/p&gt;
&lt;p&gt;Step 6. Draw the dendrogram thanks to the combination of points and heights found above. Remember that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the first combination of points was between points 2 and 4, with a height of 0.328&lt;/li&gt;
&lt;li&gt;the second combination was between points 3 and 2 &amp;amp; 4 with a height of 0.543&lt;/li&gt;
&lt;li&gt;the third combination was between points 1 and 5 with a height of 0.942&lt;/li&gt;
&lt;li&gt;the final combination was between points 1 &amp;amp; 5 and 2 &amp;amp; 3 &amp;amp; 4 with a height of 2.126167&lt;/li&gt;
&lt;li&gt;this is exactly what is illustrated in the following dendrogram:&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-35-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;solution-in-r-1&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Solution in R&lt;/h3&gt;
&lt;p&gt;To perform the hierarchical clustering with any of the 3 criterion in R, we first need to enter the data (in this case as a matrix format, but it can also be entered as a dataframe):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;X &amp;lt;- matrix(c(2.03, 0.06, -0.64, -0.10, -0.42, -0.53, -0.36, 0.07, 1.14, 0.37),
  nrow = 5, byrow = TRUE
)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;single-linkage-1&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Single linkage&lt;/h4&gt;
&lt;p&gt;We can apply the hierarchical clustering with the single linkage criterion thanks to the &lt;code&gt;hclust()&lt;/code&gt; function with the argument &lt;code&gt;method = &#34;single&#34;&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Hierarchical clustering: single linkage
hclust &amp;lt;- hclust(dist(X), method = &amp;quot;single&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the &lt;code&gt;hclust()&lt;/code&gt; function requires a distance matrix. If your data is not already a distance matrix (like in our case, as the matrix &lt;code&gt;X&lt;/code&gt; corresponds to the coordinates of the 5 points), you can transform it into a distance matrix with the &lt;code&gt;dist()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;We can now extract the heights and plot the dendrogram to check our results by hand found above:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;round(hclust$height, 3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.328 0.483 0.942 1.530&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(hclust)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-38-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;As we can see from the dendrogram, the combination of points and the heights are the same than the ones obtained by hand.&lt;/p&gt;
&lt;div id=&#34;optimal-number-of-clusters-1&#34; class=&#34;section level5&#34;&gt;
&lt;h5&gt;Optimal number of clusters&lt;/h5&gt;
&lt;p&gt;Remember that hierarchical clustering is used to determine the optimal number of clusters. This optimal number of clusters can be determined thanks to the dendrogram. For this, we usually look at the largest difference of heights:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/dendrogram-single-linkage.png&#34; style=&#34;width:100.0%&#34; alt=&#34;How to determine the number of clusters from a dendrogram? Take the largest difference of heights and count how many vertical lines you see&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;How to determine the number of clusters from a dendrogram? Take the largest difference of heights and count how many vertical lines you see&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The largest difference of heights in the dendrogram occurs before the final combination, that is, before the combination of the group 2 &amp;amp; 3 &amp;amp; 4 with the group 1 &amp;amp; 5. To determine the optimal number of clusters, simply count how many vertical lines you see within this largest difference. In our case, the optimal number of clusters is thus 2.&lt;/p&gt;
&lt;p&gt;In R, we can even highlight these two clusters directly in the dendrogram with the &lt;code&gt;rect.hclust()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(hclust)
rect.hclust(hclust,
  k = 2, # k is used to specify the number of clusters
  border = &amp;quot;blue&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-39-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Note that determining the optimal number of clusters via the dendrogram is not specific to the single linkage, it can be applied to other linkage methods too!&lt;/p&gt;
&lt;p&gt;Below another figure explaining how to determine the optimal number of clusters:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/optimal%20number%20of%20clusters%20hierarchical%20clustering.png&#34; style=&#34;width:100.0%&#34; alt=&#34;How to determine the optimal numbers of cluster in hierarchical clustering? Source: Towards Data Science&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;How to determine the optimal numbers of cluster in hierarchical clustering? Source: Towards Data Science&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;(See this &lt;a href=&#34;https://statsandr.com/blog/files/Hierarchical-clustering-cheatsheet.pdf&#34;&gt;hierarchical clustering cheatsheet&lt;/a&gt; for more visualizations like this.)&lt;/p&gt;
&lt;p&gt;Finally, we could also determine the optimal number of cluster thanks to a barplot of the heights (stored in &lt;code&gt;$height&lt;/code&gt; of the clustering output):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;barplot(hclust$height,
  names.arg = (nrow(X) - 1):1 # show the number of cluster below each bars
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-40-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Again, look for the largest jump of heights. In our case, the largest jump is from 1 to 2 classes. Therefore, the optimal number of classes is 2.&lt;/p&gt;
&lt;p&gt;Note that determining the number of clusters using the dendrogram or barplot is not a strict rule. You can also consider other methods such as the &lt;em&gt;silhouette plot&lt;/em&gt;, &lt;em&gt;elbow plot&lt;/em&gt; or some numerical measures like Dunn’s index, Hubert’s gamma, etc., which show the variation of the error with the number of clusters (&lt;em&gt;k&lt;/em&gt;), and you choose the value of &lt;em&gt;k&lt;/em&gt; where the error is smallest. Furthermore, measuring the goodness of clusters can be done thanks to the Dunn’s Index (the higher the index, the better).&lt;/p&gt;
&lt;p&gt;However, these methods are beyond the scope of this article and the method presented with the dendrogram is generally sufficient. See more detailed information in this &lt;a href=&#34;http://www.sthda.com/english/wiki/wiki.php?id_contents=7952&#34; target=&#34;_blank&#34;&gt;article&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Note that hierarchical clustering is a bit different than &lt;em&gt;k&lt;/em&gt;-means in the sense that is does not return a vector containing the information about which cluster the observations belong to. Instead, it creates a hierarchical structure (a dendrogram), a tree from which we can cut branches to get a given number of clusters. This information can be found via the &lt;code&gt;cutree()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;clust &amp;lt;- cutree(hclust,
  k = 2
)
clust&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1 2 2 2 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We see that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;points 1 and 5 belong to the cluster 1&lt;/li&gt;
&lt;li&gt;points 2, 3 and 4 belong to the cluster 2&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This is exactly what was drawn in the dendrogram above, and if needed, this information can be added to the initial data:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;X_clust &amp;lt;- cbind(X, clust)
X_clust&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##                  clust
## [1,]  2.03  0.06     1
## [2,] -0.64 -0.10     2
## [3,] -0.42 -0.53     2
## [4,] -0.36  0.07     2
## [5,]  1.14  0.37     1&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;complete-linkage-1&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Complete linkage&lt;/h4&gt;
&lt;p&gt;We can apply the hierarchical clustering with the complete linkage criterion thanks to the &lt;code&gt;hclust()&lt;/code&gt; function with the argument &lt;code&gt;method = &#34;complete&#34;&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Hierarchical clustering: complete linkage
hclust &amp;lt;- hclust(dist(X), method = &amp;quot;complete&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the &lt;code&gt;hclust()&lt;/code&gt; function requires a distance matrix. If your data is not already a distance matrix (like in our case, as the matrix &lt;code&gt;X&lt;/code&gt; corresponds to the coordinates of the 5 points), you can transform it into a distance matrix with the &lt;code&gt;dist()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;We can now extract the heights and plot the dendrogram to check our results by hand found above:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;round(hclust$height, 3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.328 0.603 0.942 2.675&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(hclust)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-44-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;As we can see from the dendrogram, the combination of points and the heights are the same than the ones obtained by hand.&lt;/p&gt;
&lt;p&gt;Similar to the single linkage, the largest difference of heights in the dendrogram occurs before the final combination, that is, before the combination of the group 2 &amp;amp; 3 &amp;amp; 4 with the group 1 &amp;amp; 5. In this case, the optimal number of clusters is thus 2. In R, we can even highlight these two clusters directly in the dendrogram with the &lt;code&gt;rect.hclust()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(hclust)
rect.hclust(hclust,
  k = 2, # k is used to specify the number of clusters
  border = &amp;quot;blue&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-45-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;average-linkage-1&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Average linkage&lt;/h4&gt;
&lt;p&gt;We can apply the hierarchical clustering with the average linkage criterion thanks to the &lt;code&gt;hclust()&lt;/code&gt; function with the argument &lt;code&gt;method = &#34;average&#34;&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Hierarchical clustering: average linkage
hclust &amp;lt;- hclust(dist(X), method = &amp;quot;average&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the &lt;code&gt;hclust()&lt;/code&gt; function requires a distance matrix. If your data is not already a distance matrix (like in our case, as the matrix &lt;code&gt;X&lt;/code&gt; corresponds to the coordinates of the 5 points), you can transform it into a distance matrix with the &lt;code&gt;dist()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;We can now extract the heights and plot the dendrogram to check our results by hand found above:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;round(hclust$height, 3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.328 0.543 0.942 2.126&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(hclust)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-47-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;As we can see from the dendrogram, the combination of points and the heights are the same than the ones obtained by hand.&lt;/p&gt;
&lt;p&gt;Like the single and complete linkages, the largest difference of heights in the dendrogram occurs before the final combination, that is, before the combination of the group 2 &amp;amp; 3 &amp;amp; 4 with the group 1 &amp;amp; 5. In this case, the optimal number of clusters is thus 2. In R, we can even highlight these two clusters directly in the dendrogram with the &lt;code&gt;rect.hclust()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(hclust)
rect.hclust(hclust,
  k = 2, # k is used to specify the number of clusters
  border = &amp;quot;blue&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/clustering-analysis-k-means-and-hierarchical-clustering-by-hand-and-in-r_files/figure-html/unnamed-chunk-48-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;k-means-versus-hierarchical-clustering&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;&lt;em&gt;k&lt;/em&gt;-means versus hierarchical clustering&lt;/h1&gt;
&lt;p&gt;Clustering is rather a subjective statistical analysis and there can be more than one appropriate algorithm, depending on the dataset at hand or the type of problem to be solved. So choosing between &lt;em&gt;k&lt;/em&gt;-means and hierarchical clustering is not always easy. Moreover, no method is better than the other, each come with their sets of limitations and benefits.&lt;/p&gt;
&lt;p&gt;If you have a good reason to think that there is a &lt;strong&gt;specific number of clusters&lt;/strong&gt; in your dataset (for example if you would like to distinguish diseased and healthy patients depending on some characteristics but you do not know in which group patients belong to), you should probably opt for the &lt;em&gt;k&lt;/em&gt;-means clustering as this technique is used when the number of groups is specified in advance. If you do not have any reason to believe there is a certain number of groups in your dataset (for instance in marketing when trying to distinguish clients without any prior belief on the number of different types of customers), then you should probably opt for the hierarchical clustering to determine in how many clusters your data should be divided.&lt;/p&gt;
&lt;p&gt;In addition to this, if you are still undecided note that, on the one hand, with a large number of variables, &lt;em&gt;k&lt;/em&gt;-means may be computationally faster than hierarchical clustering if the number of clusters is small. On the other hand, the result of a hierarchical clustering is a structure that is more informative and interpretable than the unstructured set of flat clusters returned by &lt;em&gt;k&lt;/em&gt;-means. Therefore, it is easier to determine the optimal number of clusters by looking at the dendrogram of a hierarchical clustering than trying to predict this optimal number in advance in case of &lt;em&gt;k&lt;/em&gt;-means.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;whats-next&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;What’s next?&lt;/h1&gt;
&lt;p&gt;We have seen that clustering is a nice tool to identify homogeneous observations with respect to the measured variables. Following your clustering, you may want to get a sense of the characteristics of each cluster. This can be done through some &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt; for each cluster.&lt;/p&gt;
&lt;p&gt;For example, for &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;categorical&lt;/a&gt; variables, you could start to compute, for each cluster, the proportion of responses for each level of your categorical variables. You could also visualize this information via a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#barplot&#34;&gt;barplot&lt;/a&gt;. For &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#quantitative&#34;&gt;quantitative&lt;/a&gt; variables, the mean or median response for each variable in each cluster is usually a good starting point.&lt;/p&gt;
&lt;p&gt;If your clustering performs well, you will see that within each cluster observations share a common pattern of responses across the variables. This is both a nice way to see what makes each cluster unique, and what makes clusters different.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you understand the different clustering methods and how to compute them by hand and in R.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-jaaw28m&#34; class=&#34;csl-entry&#34;&gt;
Hartigan, J. A., and M. A. Wong. 1979. &lt;span&gt;“A k-Means Clustering Algorithm.”&lt;/span&gt; &lt;em&gt;Applied Statistics&lt;/em&gt; 28: 100–108.
&lt;/div&gt;
&lt;div id=&#34;ref-lloyd1982least&#34; class=&#34;csl-entry&#34;&gt;
Lloyd, Stuart. 1982. &lt;span&gt;“Least Squares Quantization in PCM.”&lt;/span&gt; &lt;em&gt;IEEE Transactions on Information Theory&lt;/em&gt; 28 (2): 129–37.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Do my data follow a normal distribution? A note on the most widely used distribution and how to test for normality in R</title>
      <link>https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/</link>
      <pubDate>Wed, 29 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#what-is-a-normal-distribution&#34; id=&#34;toc-what-is-a-normal-distribution&#34;&gt;What is a normal distribution?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#empirical-rule&#34; id=&#34;toc-empirical-rule&#34;&gt;Empirical rule&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#parameters&#34; id=&#34;toc-parameters&#34;&gt;Parameters&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#probabilities-and-standard-normal-distribution&#34; id=&#34;toc-probabilities-and-standard-normal-distribution&#34;&gt;Probabilities and standard normal distribution&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#areas-under-the-normal-distribution-in-r-and-by-hand&#34; id=&#34;toc-areas-under-the-normal-distribution-in-r-and-by-hand&#34;&gt;Areas under the normal distribution in R and by hand&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#ex.-1&#34; id=&#34;toc-ex.-1&#34;&gt;Ex. 1&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#in-r&#34; id=&#34;toc-in-r&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand&#34; id=&#34;toc-by-hand&#34;&gt;By hand&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#ex.-2&#34; id=&#34;toc-ex.-2&#34;&gt;Ex. 2&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#in-r-1&#34; id=&#34;toc-in-r-1&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand-1&#34; id=&#34;toc-by-hand-1&#34;&gt;By hand&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#ex.-3&#34; id=&#34;toc-ex.-3&#34;&gt;Ex. 3&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#in-r-2&#34; id=&#34;toc-in-r-2&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand-2&#34; id=&#34;toc-by-hand-2&#34;&gt;By hand&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#ex.-4&#34; id=&#34;toc-ex.-4&#34;&gt;Ex. 4&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#in-r-3&#34; id=&#34;toc-in-r-3&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand-3&#34; id=&#34;toc-by-hand-3&#34;&gt;By hand&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#ex.-5&#34; id=&#34;toc-ex.-5&#34;&gt;Ex. 5&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#why-is-the-normal-distribution-so-crucial-in-statistics&#34; id=&#34;toc-why-is-the-normal-distribution-so-crucial-in-statistics&#34;&gt;Why is the normal distribution so crucial in statistics?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#how-to-test-the-normality-assumption&#34; id=&#34;toc-how-to-test-the-normality-assumption&#34;&gt;How to test the normality assumption&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#histogram&#34; id=&#34;toc-histogram&#34;&gt;Histogram&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#density-plot&#34; id=&#34;toc-density-plot&#34;&gt;Density plot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#qq-plot&#34; id=&#34;toc-qq-plot&#34;&gt;QQ-plot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#normality-test&#34; id=&#34;toc-normality-test&#34;&gt;Normality test&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/Do-my-data-follow-a-normal-distribution.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;what-is-a-normal-distribution&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;What is a normal distribution?&lt;/h1&gt;
&lt;p&gt;The normal distribution is a function that defines how a set of measurements is distributed around the center of these measurements (i.e., the mean). Many natural phenomena in real life can be approximated by a bell-shaped frequency distribution known as the normal distribution or the Gaussian distribution.&lt;/p&gt;
&lt;p&gt;The normal distribution is a mount-shaped, unimodal and symmetric distribution where most measurements gather around the mean. Moreover, the further a measure deviates from the mean, the lower the probability of occurring. In this sense, for a given variable, it is common to find values close to the mean, but less and less likely to find values as we move away from the mean. Last but not least, since the normal distribution is symmetric around its mean, extreme values in both tails of the distribution are equivalently unlikely. For instance, given that adult height follows a normal distribution, most adults are close to the average height and extremely short adults occur as infrequently as extremely tall adults.&lt;/p&gt;
&lt;p&gt;In this article, the focus is on understanding the normal distribution, the associated empirical rule, its parameters and how to compute &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-scores to find probabilities under the curve (illustrated with examples). As it is a requirement in some &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt; and &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt;, we also show 4 complementary methods to test the normality assumption in R.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;empirical-rule&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Empirical rule&lt;/h1&gt;
&lt;p&gt;Data possessing an approximately normal distribution have a definite variation, as expressed by the following empirical rule:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\mu \pm \sigma\)&lt;/span&gt; includes approximately 68% of the observations&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\mu \pm 2 \cdot \sigma\)&lt;/span&gt; includes approximately 95% of the observations&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\mu \pm 3 \cdot \sigma\)&lt;/span&gt; includes almost all of the observations (99.7% to be more precise)&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/empirical-rule-normal-distribution.png&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Normal distribution &amp;amp; empirical rule (68-95-99.7% rule)&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\sigma\)&lt;/span&gt; correspond to the population mean and population standard deviation, respectively.&lt;/p&gt;
&lt;p&gt;The empirical rule, also known as the 68-95-99.7% rule, is illustrated by the following 2 examples.&lt;/p&gt;
&lt;p&gt;Suppose that the scores of an exam in statistics given to all students in a Belgian university are known to have, approximately, a normal distribution with mean &lt;span class=&#34;math inline&#34;&gt;\(\mu = 67\)&lt;/span&gt; and standard deviation &lt;span class=&#34;math inline&#34;&gt;\(\sigma = 9\)&lt;/span&gt;. It can then be deduced that approximately 68% of the scores are between 58 and 76, that approximately 95% of the scores are between 49 and 85, and that almost all of the scores (99.7%) are between 40 and 94. Thus, knowing the mean and the standard deviation gives us a fairly good picture of the distribution of scores.&lt;/p&gt;
&lt;p&gt;Now suppose that a single university student is randomly selected from those who took the exam. What is the probability that her score will be between 49 and 85? Based on the empirical rule, we find that 0.95 is a reasonable answer to this probability question.&lt;/p&gt;
&lt;p&gt;The utility and value of the empirical rule are due to the common occurrence of approximately normal distributions of measurements in nature. For example, IQ, shoe size, height, birth weight, etc. are approximately normally-distributed. You will find that approximately 95% of these measurements will be within &lt;span class=&#34;math inline&#34;&gt;\(2\sigma\)&lt;/span&gt; of their mean &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-wackerly2014mathematical&#34; role=&#34;doc-biblioref&#34;&gt;Wackerly, Mendenhall, and Scheaffer 2014&lt;/a&gt;)&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;parameters&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Parameters&lt;/h1&gt;
&lt;p&gt;Like many probability distributions, the shape and probabilities of the normal distribution is defined entirely by some parameters. The normal distribution has two parameters:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#mean&#34;&gt;mean &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt;&lt;/a&gt;, and&lt;/li&gt;
&lt;li&gt;the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#variance&#34;&gt;variance &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2\)&lt;/span&gt;&lt;/a&gt; (i.e., the square of the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#standard-deviation&#34;&gt;standard deviation &lt;span class=&#34;math inline&#34;&gt;\(\sigma\)&lt;/span&gt;&lt;/a&gt;).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The mean &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; locates the center of the distribution, that is, the central tendency of the observations, and the variance &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2\)&lt;/span&gt; defines the width of the distribution, that is, the spread of the observations.&lt;/p&gt;
&lt;p&gt;The mean &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; can take on any finite value (i.e., &lt;span class=&#34;math inline&#34;&gt;\(-\infty &amp;lt; \mu &amp;lt; \infty\)&lt;/span&gt;), whereas the variance &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2\)&lt;/span&gt; can assume any positive finite value (i.e., &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2 &amp;gt; 0\)&lt;/span&gt;). The shape of the normal distribution changes based on these two parameters. Since there is an infinite number of combinations of the mean and variance, there is an infinite number of normal distributions, and thus an infinite number of forms.&lt;/p&gt;
&lt;p&gt;For instance, see how the shapes of the normal distributions vary when the two parameters change:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-1-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-1-2.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;As you can see on the second graph, when the variance (or the standard deviation) decreases, the observations are closer to the mean. On the contrary, when the variance (or standard deviation) increases, it is more likely that observations will be further away from the mean.&lt;/p&gt;
&lt;p&gt;A random variable &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; which follows a normal distribution with a mean of 430 and a variance of 17 is denoted &lt;span class=&#34;math inline&#34;&gt;\(X ~ \sim \mathcal{N}(\mu = 430, \sigma^2 = 17)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;We have seen that, although different normal distributions have different shapes, all normal distributions have common characteristics:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;They are symmetric, 50% of the population is above the mean and 50% of the population is below the mean&lt;/li&gt;
&lt;li&gt;The mean, median and mode are equal&lt;/li&gt;
&lt;li&gt;The empirical rule detailed earlier is applicable to all normal distributions&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;probabilities-and-standard-normal-distribution&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Probabilities and standard normal distribution&lt;/h1&gt;
&lt;p&gt;Probabilities and quantiles for random variables with normal distributions are easily found using R via the functions &lt;code&gt;pnorm()&lt;/code&gt; and &lt;code&gt;qnorm()&lt;/code&gt;. Probabilities associated with a normal distribution can also be found using this &lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-101/&#34; target=&#34;_blank&#34; rel=&#34;noopener&#34;&gt;Shiny app&lt;/a&gt;. However, before computing probabilities, we need to learn more about the standard normal distribution and the &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score.&lt;/p&gt;
&lt;p&gt;Although there are infinitely many normal distributions (since there is a normal distribution for every combination of mean and variance), we need only one table to find the probabilities under the normal curve: the &lt;strong&gt;standard normal distribution&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The normal standard distribution is a special case of the normal distribution where the mean is equal to 0 and the variance is equal to 1. A normal random variable &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; can always be transformed to a standard normal random variable &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;, a process known as “scaling” or “standardization”, by subtracting the mean from the observation, and dividing the result by the standard deviation. Formally:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[Z = \frac{x - \mu}{\sigma}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt; is the observation, &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\sigma\)&lt;/span&gt; the mean and standard deviation of the population from which the observation was drawn. So the mean of the standard normal distribution is 0, and its variance is 1, denoted &lt;span class=&#34;math inline&#34;&gt;\(Z ~ \sim \mathcal{N}(\mu = 0, \sigma^2 = 1)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;From this formula, we see that &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;, referred as standard score or &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score, allows to see how far away one specific observation is from the mean of all observations, with the distance expressed in standard deviations. In other words, the &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score corresponds to the number of standard deviations an observation is away from the mean. A positive &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score means that the specific observation is above the mean, whereas a negative &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score means that the specific observation is below the mean. &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-scores are often used to compare an individual to her peers, or more generally, a measurement compared to its distribution.&lt;/p&gt;
&lt;p&gt;For instance, suppose a student scoring 60 at a statistics exam with the mean score of the class being 40, and scoring 65 at an economics exam with the mean score of the class being 80. Given the “raw” scores, one would say that the student performed better in economics than in statistics. However, taking into consideration her peers, it is clear that the student performed &lt;em&gt;relatively&lt;/em&gt; better in statistics than in economics.&lt;/p&gt;
&lt;p&gt;Computing &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-scores allows to take into consideration all other students (i.e., the entire distribution) and gives a better measure of comparison. Let’s compute the &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-scores for the two exams, assuming that the score for both exams follow a normal distribution with the following parameters:&lt;/p&gt;
&lt;center&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Statistics&lt;/th&gt;
&lt;th&gt;Economics&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Mean&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;40&lt;/td&gt;
&lt;td&gt;80&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Standard deviation&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;8&lt;/td&gt;
&lt;td&gt;12.5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Student’s score&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;60&lt;/td&gt;
&lt;td&gt;65&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-scores for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Statistics: &lt;span class=&#34;math inline&#34;&gt;\(z_{stat} = \frac{60 - 40}{8} = 2.5\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Economics: &lt;span class=&#34;math inline&#34;&gt;\(z_{econ} = \frac{65 - 80}{12.5} = -1.2\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;On the one hand, the &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score for the exam in statistics is positive (&lt;span class=&#34;math inline&#34;&gt;\(z_{stat} = 2.5\)&lt;/span&gt;) which means that she performed better than average. On the other hand, her score for the exam in economics is negative (&lt;span class=&#34;math inline&#34;&gt;\(z_{econ} = -1.2\)&lt;/span&gt;) which means that she performed worse than average. Below an illustration of her grades in a standard normal distribution for better comparison:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-2-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Although the score in economics is better in absolute terms, the score in statistics is actually relatively better when comparing each score within its own distribution.&lt;/p&gt;
&lt;p&gt;Furthermore, &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score also enables to compare observations that would otherwise be impossible because they have different units for example. Suppose you want to compare a salary in € with a weight in kg. Without standardization, there is no way to conclude whether someone is more extreme in terms of her wage or in terms of her weight. Thanks to &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-scores, we can compare two values that were in the first place not comparable to each other.&lt;/p&gt;
&lt;p&gt;Final remark regarding the interpretation of a &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score: a rule of thumb is that an observation with a &lt;span class=&#34;math inline&#34;&gt;\(z\)&lt;/span&gt;-score between -3 and -2 or between 2 and 3 is considered as a rare value. An observation with a &lt;span class=&#34;math inline&#34;&gt;\(z\)&lt;/span&gt;-score smaller than -3 or larger than 3 is considered as an extremely rare value. A value with any other &lt;span class=&#34;math inline&#34;&gt;\(z\)&lt;/span&gt;-score is considered as not rare nor extremely rare.&lt;/p&gt;
&lt;div id=&#34;areas-under-the-normal-distribution-in-r-and-by-hand&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Areas under the normal distribution in R and by hand&lt;/h2&gt;
&lt;p&gt;Now that we have covered the &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score, we are going to use it to determine the area under the curve of a normal distribution.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note that there are several ways to arrive at the solution in the following exercises. You may therefore use other steps than the ones presented to obtain the same result.&lt;/em&gt;&lt;/p&gt;
&lt;div id=&#34;ex.-1&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Ex. 1&lt;/h3&gt;
&lt;p&gt;Let &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt; denote a normal random variable with mean 0 and standard deviation 1, find &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;We actually look for the shaded area in the following figure:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/Screenshot%202020-01-30%20at%2014.18.54.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Standard normal distribution: &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1)\)&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;In R&lt;/h4&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;pnorm(1,
  mean = 0,
  sd = 1, # sd stands for standard deviation
  lower.tail = FALSE
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.1586553&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We look for the probability of &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt; being larger than 1 so we set the argument &lt;code&gt;lower.tail = FALSE&lt;/code&gt;. The default &lt;code&gt;lower.tail = TRUE&lt;/code&gt; would give the result for &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;lt; 1)\)&lt;/span&gt;. Note that &lt;span class=&#34;math inline&#34;&gt;\(P(Z = 1) = 0\)&lt;/span&gt; so writing &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1)\)&lt;/span&gt; or &lt;span class=&#34;math inline&#34;&gt;\(P(Z \ge 1)\)&lt;/span&gt; is equivalent.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;by-hand&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;By hand&lt;/h4&gt;
&lt;p&gt;See that the random variable &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt; has already a mean of 0 and a standard deviation of 1, so no transformation is required. To find the probabilities by hand, we need to refer to the standard normal distribution table shown below:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/Screenshot%202020-01-30%20at%2015.07.44.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Standard normal distribution table &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-wackerly2014mathematical&#34; role=&#34;doc-biblioref&#34;&gt;Wackerly, Mendenhall, and Scheaffer 2014&lt;/a&gt;)&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;From the illustration at the top of the table, we see that the values inside the table correspond to the area under the normal curve &lt;strong&gt;above&lt;/strong&gt; a certain &lt;span class=&#34;math inline&#34;&gt;\(z\)&lt;/span&gt;. Since we are looking precisely at the probability above &lt;span class=&#34;math inline&#34;&gt;\(z = 1\)&lt;/span&gt; (since we look for &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1)\)&lt;/span&gt;), we can simply proceed down the first (&lt;span class=&#34;math inline&#34;&gt;\(z\)&lt;/span&gt;) column in the table until &lt;span class=&#34;math inline&#34;&gt;\(z = 1.0\)&lt;/span&gt;. The probability is 0.1587. Thus, &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1) = 0.1587\)&lt;/span&gt;. This is similar to what we found using R, except that values in the table are rounded to 4 digits.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;ex.-2&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Ex. 2&lt;/h3&gt;
&lt;p&gt;Let &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt; denote a normal random variable with mean 0 and standard deviation 1, find &lt;span class=&#34;math inline&#34;&gt;\(P(−1 \le Z \le 1)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;We are looking for the shaded area in the following figure:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/Screenshot%202020-01-30%20at%2014.19.14.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Standard normal distribution: &lt;span class=&#34;math inline&#34;&gt;\(P(−1 \le Z \le 1)\)&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r-1&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;In R&lt;/h4&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;pnorm(1, lower.tail = TRUE) - pnorm(-1, lower.tail = TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.6826895&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the arguments by default for the mean and the standard deviation are &lt;code&gt;mean = 0&lt;/code&gt; and &lt;code&gt;sd = 1&lt;/code&gt;. Since this is what we need, we can omit them.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;by-hand-1&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;By hand&lt;/h4&gt;
&lt;p&gt;For this exercise we proceed by steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;The shaded area corresponds to the entire area under the normal curve minus the two white areas in both tails of the curve.&lt;/li&gt;
&lt;li&gt;We know that the normal distribution is symmetric.&lt;/li&gt;
&lt;li&gt;Therefore, the shaded area is the entire area under the curve minus two times the white area in the right tail of the curve, the white area in the right tail of the curve being &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1)\)&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;We also know that the entire area under the normal curve is 1.&lt;/li&gt;
&lt;li&gt;Thus, the shaded area is 1 minus 2 times &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1)\)&lt;/span&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(−1 \le Z \le 1) = 1 - 2 \cdot P(Z &amp;gt; 1)\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[= 1 - 2 \cdot 0.1587 = 0.6826\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1) = 0.1587\)&lt;/span&gt; has been found in the previous exercise.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;ex.-3&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Ex. 3&lt;/h3&gt;
&lt;p&gt;Let &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt; denote a normal random variable with mean 0 and standard deviation 1, find &lt;span class=&#34;math inline&#34;&gt;\(P(0 \le Z \le 1.37)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;We are looking for the shaded area in the following figure:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/Screenshot%202020-01-30%20at%2014.19.46.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Standard normal distribution: &lt;span class=&#34;math inline&#34;&gt;\(P(0 \le Z \le 1.37)\)&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r-2&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;In R&lt;/h4&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;pnorm(0, lower.tail = FALSE) - pnorm(1.37, lower.tail = FALSE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.4146565&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;by-hand-2&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;By hand&lt;/h4&gt;
&lt;p&gt;Again we proceed by steps for this exercise:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;We know that &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 0) = 0.5\)&lt;/span&gt; since the entire area under the curve is 1, half of it is 0.5.&lt;/li&gt;
&lt;li&gt;The shaded area is half of the entire area under the curve minus the area from 1.37 to infinity.&lt;/li&gt;
&lt;li&gt;The area under the curve from 1.37 to infinity corresponds to &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1.37)\)&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;Therefore, the shaded area is &lt;span class=&#34;math inline&#34;&gt;\(0.5 - P(Z &amp;gt; 1.37)\)&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;To find &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1.37)\)&lt;/span&gt;, proceed down the &lt;span class=&#34;math inline&#34;&gt;\(z\)&lt;/span&gt; column in the table to the entry 1.3 and then across the top of the table to the column labeled .07 to read &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1.37) = .0853\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Thus,&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(0 \le Z \le 1.37) = P(Z &amp;gt; 0) - P(Z &amp;gt; 1.37)\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[ = 0.5 - 0.0853 = 0.4147\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;ex.-4&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Ex. 4&lt;/h3&gt;
&lt;p&gt;Recap the example presented in the empirical rule: Suppose that the scores of an exam in statistics given to all students in a Belgian university are known to have a normal distribution with mean &lt;span class=&#34;math inline&#34;&gt;\(\mu = 67\)&lt;/span&gt; and standard deviation &lt;span class=&#34;math inline&#34;&gt;\(\sigma = 9\)&lt;/span&gt;. What fraction of the scores lies between 70 and 80?&lt;/p&gt;
&lt;p&gt;We are looking for the shaded area in the following figure:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/Screenshot%202020-01-30%20at%2016.24.30.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(P(70 \le X \le 80)\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(X \sim \mathcal{N}(\mu = 67, \sigma^2 = 9^2)\)&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r-3&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;In R&lt;/h4&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;pnorm(70, mean = 67, sd = 9, lower.tail = FALSE) - pnorm(80, mean = 67, sd = 9, lower.tail = FALSE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.2951343&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;by-hand-3&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;By hand&lt;/h4&gt;
&lt;p&gt;Remind that we are looking for &lt;span class=&#34;math inline&#34;&gt;\(P(70 \le X \le 80)\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(X \sim \mathcal{N}(\mu = 67, \sigma^2 = 9^2)\)&lt;/span&gt;. The random variable &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; is in its “raw” format, meaning that it has not been standardized yet since the mean is 67 and the variance is &lt;span class=&#34;math inline&#34;&gt;\(9^2\)&lt;/span&gt;. We thus need to first apply the transformation to standardize the endpoints 70 and 80 with the following formula:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[Z = \frac{X - \mu}{\sigma}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;After the standardization, &lt;span class=&#34;math inline&#34;&gt;\(x = 70\)&lt;/span&gt; becomes (in terms of &lt;span class=&#34;math inline&#34;&gt;\(z\)&lt;/span&gt;, so in terms of deviation from the mean expressed in standard deviation):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[z = \frac{70 - 67}{9} = 0.3333\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;and &lt;span class=&#34;math inline&#34;&gt;\(x = 80\)&lt;/span&gt; becomes:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[z = \frac{80 - 67}{9} = 1.4444\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The figure above in terms of &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; is now in terms of &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/Screenshot%202020-01-30%20at%2016.37.13.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(P(0.3333 \le Z \le 1.4444)\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(Z \sim \mathcal{N}(\mu = 0, \sigma^2 = 1)\)&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;Finding the probability &lt;span class=&#34;math inline&#34;&gt;\(P(0.3333 \le Z \le 1.4444)\)&lt;/span&gt; is similar to exercises 1 to 3:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;The shaded area corresponds to the area under the curve from &lt;span class=&#34;math inline&#34;&gt;\(z = 0.3333\)&lt;/span&gt; to &lt;span class=&#34;math inline&#34;&gt;\(z = 1.4444\)&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;In other words, the shaded area is the area under the curve from &lt;span class=&#34;math inline&#34;&gt;\(z = 0.3333\)&lt;/span&gt; to infinity minus the area under the curve from &lt;span class=&#34;math inline&#34;&gt;\(z = 1.4444\)&lt;/span&gt; to infinity.&lt;/li&gt;
&lt;li&gt;From the table, &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 0.3333) = 0.3707\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1.4444) = 0.0749\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Thus:&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(0.3333 \le Z \le 1.4444)\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[= P(Z &amp;gt; 0.3333) - P(Z &amp;gt; 1.4444)\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[= 0.3707 - 0.0749 = 0.2958\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The difference with the probability found using in R comes from the rounding.&lt;/p&gt;
&lt;p&gt;To conclude this exercise, we can say that, given that the mean scores is 67 and the standard deviation is 9, 29.58% of the students scored between 70 and 80.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;ex.-5&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Ex. 5&lt;/h3&gt;
&lt;p&gt;See another example in a context &lt;a href=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/#example&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;why-is-the-normal-distribution-so-crucial-in-statistics&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Why is the normal distribution so crucial in statistics?&lt;/h1&gt;
&lt;p&gt;The normal distribution is important for three main reasons:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Some statistical &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt; assume that the data follow a normal distribution&lt;/li&gt;
&lt;li&gt;The central limit theorem states that, for a large number of observations (usually &lt;span class=&#34;math inline&#34;&gt;\(n &amp;gt; 30\)&lt;/span&gt;), no matter what is the underlying distribution of the original variable, the distribution of the sample means (&lt;span class=&#34;math inline&#34;&gt;\(\overline{X}_n\)&lt;/span&gt;) and of the sum (&lt;span class=&#34;math inline&#34;&gt;\(S_n = \sum_{i = 1}^n X_i\)&lt;/span&gt;) may be approached by a normal distribution &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-stevens2013intermediate&#34; role=&#34;doc-biblioref&#34;&gt;Stevens 2013&lt;/a&gt;)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Linear and nonlinear &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;regression&lt;/a&gt; assume that the residuals are normally-distributed (for small sample sizes)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;It is therefore useful to know how to test for normality in R, which is the topic of next sections.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;how-to-test-the-normality-assumption&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How to test the normality assumption&lt;/h1&gt;
&lt;p&gt;As mentioned above, some &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt; require that the data follow a normal distribution, or the result of the test may be flawed.&lt;/p&gt;
&lt;p&gt;In this section, we show 4 complementary methods to determine whether your data follow a normal distribution in R.&lt;/p&gt;
&lt;div id=&#34;histogram&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Histogram&lt;/h2&gt;
&lt;p&gt;A &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt; displays the spread and shape of a distribution, so it is a good starting point to evaluate normality.&lt;/p&gt;
&lt;p&gt;Let’s have a look at the histogram of a distribution that we would expect to follow a normal distribution, the height of 1,000 adults in cm:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-7-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The normal curve with the corresponding mean and variance has been added to the histogram. The histogram follows the normal curve so the data seems to follow a normal distribution.&lt;/p&gt;
&lt;p&gt;Below the minimal code for a histogram in R with the dataset &lt;code&gt;iris&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;data(iris)
hist(iris$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-8-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;&lt;code&gt;{ggplot2}&lt;/code&gt;&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(iris) +
  aes(x = Sepal.Length) +
  geom_histogram()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-9-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Histograms are however not sufficient, particularly in the case of small samples because the number of bins greatly change its appearance. Histograms are not recommended when the number of observations is less than 20 because it does not always correctly illustrate the distribution. See two examples below with datasets of 10 and 12 observations:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-10-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-10-2.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Can you tell whether these datasets follow a normal distribution? Surprisingly, both series are generated from a normal distribution!&lt;/p&gt;
&lt;p&gt;In the remaining of the article, we will use the dataset of the 12 adults. If you would like to follow my code in your own script, here is how I generated the data:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(42)
dat_hist &amp;lt;- data.frame(
  value = rnorm(12, mean = 165, sd = 5)
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;rnorm()&lt;/code&gt; function generates random numbers from a normal distribution (12 random numbers with a mean of 165 and standard deviation of 5 in this case). These 12 observations are then saved in the dataset called &lt;code&gt;dat_hist&lt;/code&gt; under the variable &lt;code&gt;value&lt;/code&gt;. Note that &lt;code&gt;set.seed(42)&lt;/code&gt; is important to obtain the exact same data as me.&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;density-plot&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Density plot&lt;/h2&gt;
&lt;p&gt;&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#density-plot&#34;&gt;Density plots&lt;/a&gt; also provide a visual judgment about whether the data follow a normal distribution.&lt;/p&gt;
&lt;p&gt;They are similar to histograms as they also allow to analyze the spread and the shape of the distribution. However, they are a smoothed version of the histogram.&lt;/p&gt;
&lt;p&gt;Here is the density plot drawn from the dataset on the height of the 12 adults discussed above:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(density(dat_hist$value))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-12-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggpubr}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggpubr) # package must be installed first
ggdensity(dat_hist$value,
  main = &amp;quot;Density plot of adult height&amp;quot;,
  xlab = &amp;quot;Height (cm)&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-13-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Since it is hard to test for normality from histograms and density plots only, it is recommended to corroborate these graphs with a QQ-plot. QQ-plot, also known as normality plot, is the third method presented to evaluate normality.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;qq-plot&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;QQ-plot&lt;/h2&gt;
&lt;p&gt;Like histograms and density plots, &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#qq-plot&#34;&gt;QQ-plots&lt;/a&gt; allow to visually evaluate the normality assumption.&lt;/p&gt;
&lt;p&gt;Here is the QQ-plot drawn from the dataset on the height of the 12 adults discussed above:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(car)
qqPlot(dat_hist$value)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-14-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## [1] 12  2&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In &lt;code&gt;{ggpubr}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggpubr)
ggqqplot(dat_hist$value)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-15-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Instead of looking at the spread of the data (as it is the case with histograms and density plots), with QQ-plots we only need to ascertain whether the data points follow the line (sometimes referred as Henry’s line).&lt;/p&gt;
&lt;p&gt;If points are close to the reference line and within the confidence bands, the normality assumption can be considered as met. The bigger the deviation between the points and the reference line and the more they lie outside the confidence bands, the less likely that the normality condition is met. The height of these 12 adults seem to follow a normal distribution because points follow the line and all of them lie within the confidence bands.&lt;/p&gt;
&lt;p&gt;When facing a non-normal distribution as shown by the QQ-plot below (systematic departure from the reference line), the first step is usually to apply the logarithm transformation on the data and recheck to see whether the log-transformed data are normally distributed.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-16-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;If this is the case, the data are said to follow a &lt;em&gt;log-normal&lt;/em&gt; distribution. Applying the logarithm transformation can be done in R with the &lt;code&gt;log()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;Note that QQ-plots are also a convenient way to assess whether residuals from &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;linear regression&lt;/a&gt; follow a normal distribution.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;normality-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Normality test&lt;/h2&gt;
&lt;p&gt;The 3 tools presented above were a visual inspection of the normality. Nonetheless, visual inspection may sometimes be unreliable so it is also possible to formally test whether the data follow a normal distribution with statistical tests.&lt;/p&gt;
&lt;p&gt;These normality tests compare the distribution of the data to a normal distribution in order to assess whether observations show an important deviation from normality.&lt;/p&gt;
&lt;p&gt;The two most common normality tests are Shapiro-Wilk’s test and Kolmogorov-Smirnov test. Both tests have the same hypotheses, that is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: the data follow a normal distribution&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: the data do not follow a normal distribution&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Shapiro-Wilk test is recommended for normality test as it provides better power than Kolmogorov-Smirnov test.&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt; In R, the Shapiro-Wilk test of normality can be done with the function &lt;code&gt;shapiro.test()&lt;/code&gt;:&lt;a href=&#34;#fn4&#34; class=&#34;footnote-ref&#34; id=&#34;fnref4&#34;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;shapiro.test(dat_hist$value)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Shapiro-Wilk normality test
## 
## data:  dat_hist$value
## W = 0.93968, p-value = 0.4939&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From the output, we see that the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &lt;span class=&#34;math inline&#34;&gt;\(&amp;gt; 0.05\)&lt;/span&gt; implying that we do not reject the null hypothesis that the data follow a normal distribution. This test goes in the same direction than the QQ-plot, which showed no significant deviation from the normality (as all points lied within the confidence bands).&lt;/p&gt;
&lt;p&gt;It is important to note that, in practice, normality tests are often considered as too conservative in the sense that for large sample size (&lt;span class=&#34;math inline&#34;&gt;\(n &amp;gt; 50\)&lt;/span&gt;), a small deviation from the normality may cause the normality condition to be violated.&lt;/p&gt;
&lt;p&gt;A normality test is a &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis test&lt;/a&gt;, so as the sample size increases, their capacity of detecting smaller differences increases. So as the number of observations increases, the Shapiro-Wilk test becomes very sensitive even to a small deviation from normality. As a consequence, it happens that according to the normality test the data do not follow a normal distribution although the departures from the normal distribution is negligible so the data could in fact be considered to follow approximately a normal distribution. For this reason, it is often the case that the normality condition is verified based on a combination of all methods presented in this article, that is, visual inspections (with histograms and QQ-plots) and a formal inspection (with the Shapiro-Wilk test for instance).&lt;/p&gt;
&lt;p&gt;I personally tend to prefer QQ-plots over histograms and normality tests so I do not have to bother about the sample size. This article showed the different methods that are available, your choice will of course depends on the type of your data and the context of your analyses.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope the article helped you to learn more about the normal distribution and how to test for normality in R.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-stevens2013intermediate&#34; class=&#34;csl-entry&#34;&gt;
Stevens, James P. 2013. &lt;em&gt;Intermediate Statistics: A Modern Approach&lt;/em&gt;. Routledge.
&lt;/div&gt;
&lt;div id=&#34;ref-wackerly2014mathematical&#34; class=&#34;csl-entry&#34;&gt;
Wackerly, Dennis, William Mendenhall, and Richard L Scheaffer. 2014. &lt;em&gt;Mathematical Statistics with Applications&lt;/em&gt;. Cengage Learning.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;The argument &lt;code&gt;lower.tail = TRUE&lt;/code&gt; is also the default so we could omit it as well. However, for clarity and to make sure I compute the propabilities in the correct side of the curve, I used to keep this argument explicit by writing it.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;The &lt;code&gt;set.seed()&lt;/code&gt; function accepts any numeric as argument. Generating random numbers (via &lt;code&gt;rnorm()&lt;/code&gt; for instance) implies that R will generates different random numbers every time you generate these random numbers (so every time you run the function &lt;code&gt;rnorm()&lt;/code&gt;). To make sure R generates the exact same numbers every time you run the function, a seed can be set with the function &lt;code&gt;set.seed()&lt;/code&gt;. Setting a seed implies that R will generate random numbers, but these numbers will always be the same as long as the seed is the same. This allows to replicate results that are based on a random generation. Change the seed if you want to generate other random values.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;The Shapiro-Wilk test is based on the correlation between the sample and the corresponding normal scores.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;In R, the Kolmogorov-Smirnov test is performed with the function &lt;code&gt;ks.test()&lt;/code&gt;.&lt;a href=&#34;#fnref4&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Fisher&#39;s exact test in R: independence test for a small sample</title>
      <link>https://statsandr.com/blog/fisher-s-exact-test-in-r-independence-test-for-a-small-sample/</link>
      <pubDate>Tue, 28 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/fisher-s-exact-test-in-r-independence-test-for-a-small-sample/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#hypotheses&#34; id=&#34;toc-hypotheses&#34;&gt;Hypotheses&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#example&#34; id=&#34;toc-example&#34;&gt;Example&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#data&#34; id=&#34;toc-data&#34;&gt;Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#observed-frequencies&#34; id=&#34;toc-observed-frequencies&#34;&gt;Observed frequencies&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#expected-frequencies&#34; id=&#34;toc-expected-frequencies&#34;&gt;Expected frequencies&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#fishers-exact-test-in-r&#34; id=&#34;toc-fishers-exact-test-in-r&#34;&gt;Fisher’s exact test in R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion-and-interpretation&#34; id=&#34;toc-conclusion-and-interpretation&#34;&gt;Conclusion and interpretation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#combination-of-plot-and-statistical-test&#34; id=&#34;toc-combination-of-plot-and-statistical-test&#34;&gt;Combination of plot and statistical test&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/fisher-s-exact-test-in-r-independence-test-for-a-small-sample_files/0_73Z2pBxY4UbGaVXz.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;After presenting the &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-by-hand/&#34;&gt;Chi-square test of independence by hand&lt;/a&gt; and &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;in R&lt;/a&gt;, this article focuses on the Fisher’s exact test.&lt;/p&gt;
&lt;p&gt;Independence tests are used to determine if there is a significant relationship between two categorical variables. There exists two different types of independence test:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the Chi-square test (the most common)&lt;/li&gt;
&lt;li&gt;the Fisher’s exact test&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;On the one hand, the Chi-square test is used when the sample is large enough (in this case the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value is an approximation that becomes exact when the sample becomes infinite, which is the case for many statistical tests). On the other hand, the Fisher’s exact test is used when the sample is small (and in this case the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value is exact and is not an approximation).&lt;/p&gt;
&lt;p&gt;The literature indicates that the usual rule for deciding whether the &lt;span class=&#34;math inline&#34;&gt;\(\chi^2\)&lt;/span&gt; approximation is good enough is that the Chi-square test is not appropriate when the &lt;strong&gt;expected&lt;/strong&gt; values in one of the cells of the contingency table is less than 5, and in this case the Fisher’s exact test is preferred &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-mccrum2008correct&#34; role=&#34;doc-biblioref&#34;&gt;McCrum-Gardner 2008&lt;/a&gt;; &lt;a href=&#34;#ref-bower2003use&#34; role=&#34;doc-biblioref&#34;&gt;Bower 2003&lt;/a&gt;)&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;hypotheses&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Hypotheses&lt;/h1&gt;
&lt;p&gt;The hypotheses of the Fisher’s exact test are the same than for the Chi-square test, that is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt; : the variables are independent, there is &lt;strong&gt;no&lt;/strong&gt; relationship between the two categorical variables. Knowing the value of one variable does not help to predict the value of the other variable&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt; : the variables are dependent, there is a relationship between the two categorical variables. Knowing the value of one variable helps to predict the value of the other variable&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;example&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Example&lt;/h1&gt;
&lt;div id=&#34;data&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Data&lt;/h2&gt;
&lt;p&gt;For our example, we want to determine whether there is a statistically significant association between smoking and being a professional athlete. Smoking can only be “yes” or “no” and being a professional athlete can only be “yes” or “no”. The two variables of interest are qualitative variables and we collected data on 14 persons.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;observed-frequencies&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Observed frequencies&lt;/h2&gt;
&lt;p&gt;Our data are summarized in the contingency table below reporting the number of people in each subgroup:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- data.frame(
  &amp;quot;smoke_no&amp;quot; = c(7, 0),
  &amp;quot;smoke_yes&amp;quot; = c(2, 5),
  row.names = c(&amp;quot;Athlete&amp;quot;, &amp;quot;Non-athlete&amp;quot;),
  stringsAsFactors = FALSE
)
colnames(dat) &amp;lt;- c(&amp;quot;Non-smoker&amp;quot;, &amp;quot;Smoker&amp;quot;)

dat&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             Non-smoker Smoker
## Athlete              7      2
## Non-athlete          0      5&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is also a good practice to draw a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#mosaic-plot&#34;&gt;mosaic plot&lt;/a&gt; to visually represent the data:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mosaicplot(dat,
  main = &amp;quot;Mosaic plot&amp;quot;,
  color = TRUE
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/fisher-s-exact-test-in-r-independence-test-for-a-small-sample_files/figure-html/unnamed-chunk-2-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;We can already see from the plot that the proportion of smokers in the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;sample&lt;/a&gt; is higher among non-athletes than athlete. The plot is however not sufficient to conclude that there is such a significant association in the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;population&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Like many &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt;, this can be done via a &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis test&lt;/a&gt;. But before seeing how to do it in R, let’s see the concept of expected frequencies.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;expected-frequencies&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Expected frequencies&lt;/h2&gt;
&lt;p&gt;Remember that the Fisher’s exact test is used when there is at least one cell in the contingency table of the expected frequencies below 5. To retrieve the expected frequencies, use the &lt;code&gt;chisq.test()&lt;/code&gt; function together with &lt;code&gt;$expected&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;chisq.test(dat)$expected&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Warning in chisq.test(dat): Chi-squared approximation may be incorrect&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             Non-smoker Smoker
## Athlete            4.5    4.5
## Non-athlete        2.5    2.5&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The contingency table above confirms that we should use the Fisher’s exact test instead of the Chi-square test because there is at least one cell below 5.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Tip&lt;/em&gt;: although it is a good practice to check the expected frequencies &lt;strong&gt;before&lt;/strong&gt; deciding between the Chi-square and the Fisher test, it is not a big issue if you forget. As you can see above, when doing the Chi-square test in R (with &lt;code&gt;chisq.test()&lt;/code&gt;), a &lt;a href=&#34;https://statsandr.com/blog/top-10-errors-in-r/#warnings&#34;&gt;warning&lt;/a&gt; such as “Chi-squared approximation may be incorrect” will appear. This warning means that the smallest expected frequencies is lower than 5. Therefore, do not worry if you forgot to check the expected frequencies before applying the appropriate test to your data, R will warn you that you should use the Fisher’s exact test instead of the Chi-square test if that is the case.&lt;/p&gt;
&lt;p&gt;(Remember that, as for the Chi-square test of independence, the observations must be independent in order for the Fisher’s exact test to be valid. See more details about the independence assumption in this &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/#chi-square-test-of-independence-in-r&#34;&gt;section&lt;/a&gt;.)&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;fishers-exact-test-in-r&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Fisher’s exact test in R&lt;/h2&gt;
&lt;p&gt;To perform the Fisher’s exact test in R, use the &lt;code&gt;fisher.test()&lt;/code&gt; function as you would do for the Chi-square test:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- fisher.test(dat)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Fisher&amp;#39;s Exact Test for Count Data
## 
## data:  dat
## p-value = 0.02098
## alternative hypothesis: true odds ratio is not equal to 1
## 95 percent confidence interval:
##  1.449481      Inf
## sample estimates:
## odds ratio 
##        Inf&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The most important in the output is the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value. You can also retrieve the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value with:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$p.value&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.02097902&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that if your data is not already presented as a contingency table, you can simply use the following code:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;fisher.test(table(dat$variable1, dat$variable2))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;where &lt;code&gt;dat&lt;/code&gt; is the name of your dataset, &lt;code&gt;variable1&lt;/code&gt; and &lt;code&gt;variable2&lt;/code&gt; correspond to the names of the two variables of interest.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion-and-interpretation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Conclusion and interpretation&lt;/h2&gt;
&lt;p&gt;From the output and from &lt;code&gt;test$p.value&lt;/code&gt; we see that the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value is less than the significance level of 5%. Like any other &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical test&lt;/a&gt;, if the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value is less than the significance level, we can reject the null hypothesis. If you are not familiar with &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values, I invite you to read this &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/#a-note-on-p-value-and-significance-level-alpha&#34;&gt;section&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(\Rightarrow\)&lt;/span&gt; In our context, rejecting the null hypothesis for the Fisher’s exact test of independence means that there is a significant relationship between the two categorical variables (smoking habits and being an athlete or not). Therefore, knowing the value of one variable helps to predict the value of the other variable.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;combination-of-plot-and-statistical-test&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Combination of plot and statistical test&lt;/h1&gt;
&lt;p&gt;It is possible print the results of the Fisher’s exact test directly on a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#barplot&#34;&gt;barplot&lt;/a&gt; thanks to the &lt;code&gt;ggbarstats()&lt;/code&gt; function from the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package (the function has been slightly edited to match our needs).&lt;/p&gt;
&lt;p&gt;It is easier to work with the package when our data is not already in the form of a contingency table so we transform it to a data frame before plotting the results:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# create dataframe from contingency table
x &amp;lt;- c()
for (row in rownames(dat)) {
  for (col in colnames(dat)) {
    x &amp;lt;- rbind(x, matrix(rep(c(row, col), dat[row, col]), ncol = 2, byrow = TRUE))
  }
}
df &amp;lt;- as.data.frame(x)
colnames(df) &amp;lt;- c(&amp;quot;Sport_habits&amp;quot;, &amp;quot;Smoking_habits&amp;quot;)
df&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    Sport_habits Smoking_habits
## 1       Athlete     Non-smoker
## 2       Athlete     Non-smoker
## 3       Athlete     Non-smoker
## 4       Athlete     Non-smoker
## 5       Athlete     Non-smoker
## 6       Athlete     Non-smoker
## 7       Athlete     Non-smoker
## 8       Athlete         Smoker
## 9       Athlete         Smoker
## 10  Non-athlete         Smoker
## 11  Non-athlete         Smoker
## 12  Non-athlete         Smoker
## 13  Non-athlete         Smoker
## 14  Non-athlete         Smoker&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Fisher&amp;#39;s exact test with raw data
test &amp;lt;- fisher.test(table(df))

# combine plot and statistical test with ggbarstats
library(ggstatsplot)
ggbarstats(
  df, Smoking_habits, Sport_habits,
  results.subtitle = FALSE,
  subtitle = paste0(
    &amp;quot;Fisher&amp;#39;s exact test&amp;quot;, &amp;quot;, p-value = &amp;quot;,
    ifelse(test$p.value &amp;lt; 0.001, &amp;quot;&amp;lt; 0.001&amp;quot;, round(test$p.value, 3))
  )
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/fisher-s-exact-test-in-r-independence-test-for-a-small-sample_files/figure-html/unnamed-chunk-7-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;From the plot, it is clear that the proportion of smokers among non-athletes is higher than among athletes, suggesting that there is a relationship between the two variables.&lt;/p&gt;
&lt;p&gt;This is confirmed thanks to the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value displayed in the subtitle of the plot. As previously, we reject the null hypothesis and we conclude that the variables smoking habits and being an athlete or not are dependent (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value = 0.021).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope the article helped you to perform the Fisher’s exact test of independence in R and interpret its results. Learn more about the Chi-square test of independence &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-by-hand/&#34;&gt;by hand&lt;/a&gt; or &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;in R&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-bower2003use&#34; class=&#34;csl-entry&#34;&gt;
Bower, Keith M. 2003. &lt;span&gt;“When to Use Fisher’s Exact Test.”&lt;/span&gt; In &lt;em&gt;American Society for Quality, Six Sigma Forum Magazine&lt;/em&gt;, 2:35–37. 4.
&lt;/div&gt;
&lt;div id=&#34;ref-mccrum2008correct&#34; class=&#34;csl-entry&#34;&gt;
McCrum-Gardner, Evie. 2008. &lt;span&gt;“Which Is the Correct Statistical Test to Use?”&lt;/span&gt; &lt;em&gt;British Journal of Oral and Maxillofacial Surgery&lt;/em&gt; 46 (1): 38–41.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;The data are the same than for the article covering the &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-by-hand/&#34;&gt;Chi-square test by hand&lt;/a&gt;, except that some observations have been removed to decrease the sample size.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Chi-square test of independence by hand</title>
      <link>https://statsandr.com/blog/chi-square-test-of-independence-by-hand/</link>
      <pubDate>Mon, 27 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/chi-square-test-of-independence-by-hand/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#hypotheses&#34; id=&#34;toc-hypotheses&#34;&gt;Hypotheses&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#how-the-test-works&#34; id=&#34;toc-how-the-test-works&#34;&gt;How the test works?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#example&#34; id=&#34;toc-example&#34;&gt;Example&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#observed-frequencies&#34; id=&#34;toc-observed-frequencies&#34;&gt;Observed frequencies&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#expected-frequencies&#34; id=&#34;toc-expected-frequencies&#34;&gt;Expected frequencies&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#test-statistic&#34; id=&#34;toc-test-statistic&#34;&gt;Test statistic&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#critical-value&#34; id=&#34;toc-critical-value&#34;&gt;Critical value&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion-and-interpretation&#34; id=&#34;toc-conclusion-and-interpretation&#34;&gt;Conclusion and interpretation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/chi-square-test-of-independence-by-hand_files/chi-square-test-of-independence-by-hand.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;Chi-square tests of independence test whether two &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;qualitative variables&lt;/a&gt; are independent, that is, whether there exists a relationship between two categorical variables. In other words, this test is used to determine whether the values of one of the 2 qualitative variables depend on the values of the other qualitative variable.&lt;/p&gt;
&lt;p&gt;If the test shows no association between the two variables (i.e., the variables are independent), it means that knowing the value of one variable gives no information about the value of the other variable. On the contrary, if the test shows a relationship between the variables (i.e., the variables are dependent), it means that knowing the value of one variable provides information about the value of the other variable.&lt;/p&gt;
&lt;p&gt;This article focuses on how to perform a Chi-square test of independence by hand and how to interpret the results with a concrete example. To learn how to do this test in R, read the article “&lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;Chi-square test of independence in R&lt;/a&gt;”.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;hypotheses&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Hypotheses&lt;/h1&gt;
&lt;p&gt;The Chi-square test of independence is a &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis test&lt;/a&gt; so it has a null (&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;) and an alternative hypothesis (&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt; : the variables are independent, there is &lt;strong&gt;no&lt;/strong&gt; relationship between the two categorical variables. Knowing the value of one variable does not help to predict the value of the other variable&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt; : the variables are dependent, there is a relationship between the two categorical variables. Knowing the value of one variable helps to predict the value of the other variable&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;how-the-test-works&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How the test works?&lt;/h1&gt;
&lt;p&gt;The Chi-square test of independence works by comparing the observed frequencies (so the frequencies observed in your sample) to the expected frequencies if there was no relationship between the two categorical variables (so the expected frequencies if the null hypothesis was true).&lt;/p&gt;
&lt;p&gt;If the difference between the observed frequencies and the expected frequencies is &lt;strong&gt;small&lt;/strong&gt;, we cannot reject the null hypothesis of independence and thus we cannot reject the fact that the two &lt;strong&gt;variables are not related&lt;/strong&gt;. On the other hand, if the difference between the observed frequencies and the expected frequencies is &lt;strong&gt;large&lt;/strong&gt;, we can reject the null hypothesis of independence and thus we can conclude that the two &lt;strong&gt;variables are related&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The threshold between a small and large difference is a value that comes from the Chi-square distribution (hence the name of the test). This value, referred as the critical value, depends on the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; (usually set equal to 5%) and on the degrees of freedom. This critical value can be found in the statistical table of the Chi-square distribution. More on this critical value and the degrees of freedom later in the article.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;example&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Example&lt;/h1&gt;
&lt;p&gt;For our example, we want to determine whether there is a statistically significant association between smoking and being a professional athlete. Smoking can only be “yes” or “no” and being a professional athlete can only be “yes” or “no”. The two variables of interest are qualitative variables so we need to use a Chi-square test of independence, and the data have been collected on 28 persons.&lt;/p&gt;
&lt;p&gt;Note that we chose binary variables (binary variables = qualitative variables with two levels) for the sake of easiness, but the Chi-square test of independence can also be performed on qualitative variables with more than two levels. For instance, if the variable smoking had three levels: (i) non-smokers, (ii) moderate smokers and (iii) heavy smokers, the steps and the interpretation of the results of the test are similar than with two levels.&lt;/p&gt;
&lt;div id=&#34;observed-frequencies&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Observed frequencies&lt;/h2&gt;
&lt;p&gt;Our data are summarized in the contingency table below reporting the number of people in each subgroup, totals by row, by column and the grand total:&lt;/p&gt;
&lt;table style=&#34;width:68%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;25%&#34; /&gt;
&lt;col width=&#34;18%&#34; /&gt;
&lt;col width=&#34;12%&#34; /&gt;
&lt;col width=&#34;12%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt; &lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;Non-smoker&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;Smoker&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;Total&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;&lt;strong&gt;Athlete&lt;/strong&gt;&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;14&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;4&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;18&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;&lt;strong&gt;Non-athlete&lt;/strong&gt;&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;0&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;&lt;strong&gt;Total&lt;/strong&gt;&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;14&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;14&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;28&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;div id=&#34;expected-frequencies&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Expected frequencies&lt;/h2&gt;
&lt;p&gt;Remember that for the Chi-square test of independence we need to determine whether the observed counts are significantly different from the counts that we would expect if there was no association between the two variables. We have the observed counts (see the table above), so we now need to compute the expected counts in the case the variables were independent. These expected frequencies are computed for each subgroup one by one with the following formula:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\text{exp. frequencies} = \frac{\text{total # of obs. for the row} \cdot \text{total # of obs. for the column}}{\text{total number of observations}}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where obs. correspond to observations. Given our table of observed frequencies above, below is the table of the expected frequencies computed for each subgroup:&lt;/p&gt;
&lt;table style=&#34;width:94%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;25%&#34; /&gt;
&lt;col width=&#34;29%&#34; /&gt;
&lt;col width=&#34;29%&#34; /&gt;
&lt;col width=&#34;11%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt; &lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;Non-smoker&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;Smoker&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;Total&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;&lt;strong&gt;Athlete&lt;/strong&gt;&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;(18 * 14) / 28 = 9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;(18 * 14) / 28 = 9&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;18&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;&lt;strong&gt;Non-athlete&lt;/strong&gt;&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;(10 * 14) / 28 = 5&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;(10 * 14) / 28 = 5&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;&lt;strong&gt;Total&lt;/strong&gt;&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;14&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;14&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;28&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Note that the Chi-square test of independence should only be done when the &lt;strong&gt;expected&lt;/strong&gt; frequencies in all groups are equal to or greater than 5. This assumption is met for our example as the minimum number of expected frequencies is 5. If the condition is not met, the &lt;a href=&#34;https://statsandr.com/blog/fisher-s-exact-test-in-r-independence-test-for-a-small-sample/&#34;&gt;Fisher’s exact test&lt;/a&gt; is preferred.&lt;/p&gt;
&lt;p&gt;Talking about assumptions, the Chi-square test of independence requires that the observations are independent. This is usually not tested formally, but rather verified based on the design of the experiment and on the good control of experimental conditions. If you are not sure, ask yourself if one observation is related to another (if one observation has an impact on another). If not, it is most likely that you have independent observations.&lt;/p&gt;
&lt;p&gt;If you have dependent observations (paired samples), the McNemar’s or Cochran’s Q tests should be used instead. The McNemar’s test is used when we want to know if there is a significant change in two paired samples (typically in a study with a measure before and after on the same subject) when the variables have only two categories. The Cochran’s Q tests is an extension of the McNemar’s test when we have more than two related measures.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;test-statistic&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Test statistic&lt;/h2&gt;
&lt;p&gt;We have the observed and expected frequencies. We now need to compare these frequencies to determine if they differ significantly. The difference between the observed and expected frequencies, referred as the test statistic (or t-stat) and denoted &lt;span class=&#34;math inline&#34;&gt;\(\chi^2\)&lt;/span&gt;, is computed as follows:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\chi^2 = \sum_{i, j} \frac{\big(O_{ij} - E_{ij}\big)^2}{E_{ij}}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(O\)&lt;/span&gt; represents the observed frequencies and &lt;span class=&#34;math inline&#34;&gt;\(E\)&lt;/span&gt; the expected frequencies. We use the square of the differences between the observed and expected frequencies to make sure that negative differences are not compensated by positive differences. The formula looks more complex than what it really is, so let’s illustrate it with our example. We first compute the difference in each subgroup one by one according to the formula:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;in the subgroup of athlete and non-smoker: &lt;span class=&#34;math inline&#34;&gt;\(\frac{(14 - 9)^2}{9} = 2.78\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;in the subgroup of non-athlete and non-smoker: &lt;span class=&#34;math inline&#34;&gt;\(\frac{(0 - 5)^2}{5} = 5\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;in the subgroup of athlete and smoker: &lt;span class=&#34;math inline&#34;&gt;\(\frac{(4 - 9)^2}{9} = 2.78\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;in the subgroup of non-athlete and smoker: &lt;span class=&#34;math inline&#34;&gt;\(\frac{(10 - 5)^2}{5} = 5\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;and then we sum them all to obtain the test statistic:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\chi^2 = 2.78 + 5 + 2.78 + 5 = 15.56\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;critical-value&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Critical value&lt;/h2&gt;
&lt;p&gt;The test statistic alone is not enough to conclude for independence or dependence between the two variables. As previously mentioned, this test statistic (which in some sense is the difference between the observed and expected frequencies) must be compared to a critical value to determine whether the difference is large or small. One cannot tell that a test statistic is large or small without putting it in perspective with the critical value.&lt;/p&gt;
&lt;p&gt;If the test statistic is above the critical value, it means that the probability of observing such a difference between the observed and expected frequencies is unlikely. On the other hand, if the test statistic is below the critical value, it means that the probability of observing such a difference is likely. If it is likely to observe this difference, we cannot reject the hypothesis that the two variables are independent, otherwise we can conclude that there exists a relationship between the variables.&lt;/p&gt;
&lt;p&gt;The critical value can be found in the statistical table of the Chi-square distribution and depends on the significance level, denoted &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;, and the degrees of freedom, denoted &lt;span class=&#34;math inline&#34;&gt;\(df\)&lt;/span&gt;. The significance level is usually set equal to 5%. The degrees of freedom for a Chi-square test of independence is found as follow:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[df = (\text{number of rows} - 1) \cdot (\text{number of columns} - 1)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In our example, the degrees of freedom is thus &lt;span class=&#34;math inline&#34;&gt;\(df = (2 - 1) \cdot (2 - 1) = 1\)&lt;/span&gt; since there are two rows and two columns in the contingency table (totals do not count as a row or column).&lt;/p&gt;
&lt;p&gt;We now have all the necessary information to find the critical value in the Chi-square table (&lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(df = 1\)&lt;/span&gt;). To find the critical value we need to look at the row &lt;span class=&#34;math inline&#34;&gt;\(df = 1\)&lt;/span&gt; and the column &lt;span class=&#34;math inline&#34;&gt;\(\chi^2_{0.050}\)&lt;/span&gt; (since &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;) in the picture below. The critical value is &lt;span class=&#34;math inline&#34;&gt;\(3.84146\)&lt;/span&gt;.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/chi-square-test-of-independence-by-hand_files/Screenshot%202020-01-28%20at%2000.56.28.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Chi-square table - Critical value for alpha = 5% and df = 1&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion-and-interpretation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Conclusion and interpretation&lt;/h2&gt;
&lt;p&gt;Now that we have the test statistic and the critical value, we can compare them to check whether the null hypothesis of independence of the variables is rejected or not. In our example,&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\text{test statistic} = 15.56 &amp;gt; \text{critical value} = 3.84146\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Like for many &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt;, when the test statistic is larger than the critical value, we can reject the null hypothesis at the specified significance level.&lt;/p&gt;
&lt;p&gt;In our case, we can therefore reject the null hypothesis of independence between the two categorical variables at the 5% significance level.&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(\Rightarrow\)&lt;/span&gt; This means that there is a significant relationship between the smoking habit and being an athlete or not. Knowing the value of one variable helps to predict the value of the other variable.&lt;/p&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope the article helped you to perform the Chi-square test of independence by hand and interpret its results. If you would like to learn how to do this test in R, read the article “&lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;Chi-square test of independence in R&lt;/a&gt;”.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;For readers that prefer to check the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value in order to reject or not the null hypothesis, I also created a &lt;a href=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/&#34;&gt;Shiny app&lt;/a&gt; to help you compute the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value given a test statistic.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Chi-square test of independence in R</title>
      <link>https://statsandr.com/blog/chi-square-test-of-independence-in-r/</link>
      <pubDate>Mon, 27 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/chi-square-test-of-independence-in-r/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#data&#34; id=&#34;toc-data&#34;&gt;Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#chi-square-test-of-independence-in-r&#34; id=&#34;toc-chi-square-test-of-independence-in-r&#34;&gt;Chi-square test of independence in R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion-and-interpretation&#34; id=&#34;toc-conclusion-and-interpretation&#34;&gt;Conclusion and interpretation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#combination-of-plot-and-statistical-test&#34; id=&#34;toc-combination-of-plot-and-statistical-test&#34;&gt;Combination of plot and statistical test&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r_files/Chi-square-test-independence-in-R.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;This article explains how to perform the Chi-square test of independence in R and how to interpret its results. To learn more about how the test works and how to do it by hand, I invite you to read the article “&lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-by-hand/&#34;&gt;Chi-square test of independence by hand&lt;/a&gt;”.&lt;/p&gt;
&lt;p&gt;To briefly recap what have been said in that article, the Chi-square test of independence tests whether there is a relationship between two &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;categorical variables&lt;/a&gt;. The null and alternative hypotheses are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt; : the variables are independent, there is &lt;strong&gt;no&lt;/strong&gt; relationship between the two categorical variables. Knowing the value of one variable does not help to predict the value of the other variable&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt; : the variables are dependent, there is a relationship between the two categorical variables. Knowing the value of one variable helps to predict the value of the other variable&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The Chi-square test of independence works by comparing the observed frequencies (so the frequencies observed in your sample) to the expected frequencies if there was no relationship between the two categorical variables (so the expected frequencies if the null hypothesis was true).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;data&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Data&lt;/h1&gt;
&lt;p&gt;For our example, let’s reuse the dataset introduced in the article “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;Descriptive statistics in R&lt;/a&gt;”. This dataset is the well-known &lt;code&gt;iris&lt;/code&gt; dataset slightly enhanced. Since there is only one categorical variable and the Chi-square test of independence requires two categorical variables, we add the variable &lt;code&gt;size&lt;/code&gt; which corresponds to &lt;code&gt;small&lt;/code&gt; if the length of the petal is smaller than the median of all flowers, &lt;code&gt;big&lt;/code&gt; otherwise:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- iris

dat$size &amp;lt;- ifelse(dat$Sepal.Length &amp;lt; median(dat$Sepal.Length),
  &amp;quot;small&amp;quot;, &amp;quot;big&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We now create a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#contingency-table&#34;&gt;contingency table&lt;/a&gt; of the two variables &lt;code&gt;Species&lt;/code&gt; and &lt;code&gt;size&lt;/code&gt; with the &lt;code&gt;table()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;table(dat$Species, dat$size)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             
##              big small
##   setosa       1    49
##   versicolor  29    21
##   virginica   47     3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The contingency table gives the observed number of cases in each subgroup. For instance, there is only one big setosa flower, while there are 49 small setosa flowers in the dataset.&lt;/p&gt;
&lt;p&gt;It is also a good practice to draw a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#barplot&#34;&gt;barplot&lt;/a&gt; to visually represent the data:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggplot2)

ggplot(dat) +
  aes(x = Species, fill = size) +
  geom_bar()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r_files/figure-html/unnamed-chunk-3-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;If you prefer to visualize it in terms of proportions (so that bars all have a height of 1, or 100%):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Species, fill = size) +
  geom_bar(position = &amp;quot;fill&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r_files/figure-html/unnamed-chunk-4-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;This second barplot is particularly useful if there are a different number of observations in each level of the variable drawn on the &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt;-axis because it allows to compare the two variables on the same ground.&lt;/p&gt;
&lt;p&gt;If you prefer to have the bars next to each other:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Species, fill = size) +
  geom_bar(position = &amp;quot;dodge&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r_files/figure-html/unnamed-chunk-5-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;See the article “&lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;Graphics in R with ggplot2&lt;/a&gt;” to learn how to create this kind of barplot in &lt;code&gt;{ggplot2}&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;chi-square-test-of-independence-in-r&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Chi-square test of independence in R&lt;/h1&gt;
&lt;p&gt;For this example, we are going to test in R if there is a relationship between the variables &lt;code&gt;Species&lt;/code&gt; and &lt;code&gt;size&lt;/code&gt;. For this, the &lt;code&gt;chisq.test()&lt;/code&gt; function is used:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- chisq.test(table(dat$Species, dat$size))
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	Pearson&amp;#39;s Chi-squared test
## 
## data:  table(dat$Species, dat$size)
## X-squared = 86.035, df = 2, p-value &amp;lt; 2.2e-16&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Everything you need appears in this output:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the title of the test,&lt;/li&gt;
&lt;li&gt;which variables have been used,&lt;/li&gt;
&lt;li&gt;the test statistic,&lt;/li&gt;
&lt;li&gt;the degrees of freedom and&lt;/li&gt;
&lt;li&gt;the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value of the test.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You can also retrieve the &lt;span class=&#34;math inline&#34;&gt;\(\chi^2\)&lt;/span&gt; test statistic and the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value with:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$statistic # test statistic&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## X-squared 
##  86.03451&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$p.value # p-value&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 2.078944e-19&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you need to find the expected frequencies, use &lt;code&gt;test$expected&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;If a warning such as “Chi-squared approximation may be incorrect” appears, it means that the smallest expected frequencies is lower than 5. To avoid this issue, you can either:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;gather some levels (especially those with a small number of observations) to increase the number of observations in the subgroups, or&lt;/li&gt;
&lt;li&gt;use the &lt;a href=&#34;https://statsandr.com/blog/fisher-s-exact-test-in-r-independence-test-for-a-small-sample/&#34;&gt;Fisher’s exact test&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The Fisher’s exact test does not require the assumption of a minimum of 5 expected counts in the contingency table. It can be applied in R thanks to the function &lt;code&gt;fisher.test()&lt;/code&gt;. This test is similar to the Chi-square test in terms of hypothesis and interpretation of the results. Learn more about this test in this &lt;a href=&#34;https://statsandr.com/blog/fisher-s-exact-test-in-r-independence-test-for-a-small-sample/&#34;&gt;article&lt;/a&gt; dedicated to this type of test.&lt;/p&gt;
&lt;p&gt;Talking about assumptions, the Chi-square test of independence requires that the observations are independent. This is usually not tested formally, but rather verified based on the design of the experiment and on the good control of experimental conditions. If you are not sure, ask yourself if one observation is related to another (if one observation has an impact on another). If not, it is most likely that you have independent observations.&lt;/p&gt;
&lt;p&gt;If you have dependent observations (paired samples), the McNemar’s or Cochran’s Q tests should be used instead. The McNemar’s test is used when we want to know if there is a significant change in two paired samples (typically in a study with a measure before and after on the same subject) when the variables have only two categories. The Cochran’s Q tests is an extension of the McNemar’s test when we have more than two related measures.&lt;/p&gt;
&lt;p&gt;For your information, there are three other methods to perform the Chi-square test of independence in R:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;with the &lt;code&gt;summary()&lt;/code&gt; function&lt;/li&gt;
&lt;li&gt;with the &lt;code&gt;assocstats()&lt;/code&gt; function from the &lt;code&gt;{vcd}&lt;/code&gt; package&lt;/li&gt;
&lt;li&gt;with the &lt;code&gt;ctable()&lt;/code&gt; function from the &lt;code&gt;{summarytools}&lt;/code&gt; package&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# second method:
summary(table(dat$Species, dat$size))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Number of cases in table: 150 
## Number of factors: 2 
## Test for independence of all factors:
## 	Chisq = 86.03, df = 2, p-value = 2.079e-19&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# third method:
library(vcd)

assocstats(table(dat$Species, dat$size))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##                      X^2 df P(&amp;gt; X^2)
## Likelihood Ratio 107.308  2        0
## Pearson           86.035  2        0
## 
## Phi-Coefficient   : NA 
## Contingency Coeff.: 0.604 
## Cramer&amp;#39;s V        : 0.757&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(summarytools)
library(dplyr)

# fourth method:
dat %$%
  ctable(Species, size,
    prop = &amp;quot;r&amp;quot;, chisq = TRUE, headings = FALSE
  ) %&amp;gt;%
  print(
    method = &amp;quot;render&amp;quot;,
    style = &amp;quot;rmarkdown&amp;quot;,
    footnote = NA
  )&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r_files/chi-square-test-of-independence-in-R-summarytools.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;As you can see all four methods give the same results.&lt;/p&gt;
&lt;p&gt;If you do not have the same &lt;em&gt;p&lt;/em&gt;-values with your data across the different methods, make sure to add the &lt;code&gt;correct = FALSE&lt;/code&gt; argument in the &lt;code&gt;chisq.test()&lt;/code&gt; function to prevent from applying the Yate’s continuity correction, which is applied by default in this method.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion-and-interpretation&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion and interpretation&lt;/h1&gt;
&lt;p&gt;From the output and from &lt;code&gt;test$p.value&lt;/code&gt; we see that the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value is less than the significance level of 5%. Like any other &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical test&lt;/a&gt;, if the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value is less than the significance level, we can reject the null hypothesis. If you are not familiar with &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-values, I invite you to read this &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/#a-note-on-p-value-and-significance-level-alpha&#34;&gt;section&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(\Rightarrow\)&lt;/span&gt; In our context, rejecting the null hypothesis for the Chi-square test of independence means that there is a significant relationship between the species and the size. Therefore, knowing the value of one variable helps to predict the value of the other variable.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;combination-of-plot-and-statistical-test&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Combination of plot and statistical test&lt;/h1&gt;
&lt;p&gt;I recently discovered the &lt;code&gt;mosaic()&lt;/code&gt; function from the &lt;code&gt;{vcd}&lt;/code&gt; package. This function has the advantage that it combines a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#mosaic-plot&#34;&gt;mosaic plot&lt;/a&gt; (to visualize a contingency table) and the result of the Chi-square test of independence:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(vcd)

mosaic(~ Species + size,
  direction = c(&amp;quot;v&amp;quot;, &amp;quot;h&amp;quot;),
  data = dat,
  shade = TRUE
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r_files/figure-html/unnamed-chunk-10-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;As you can see, the mosaic plot is similar to the barplot presented above, but the &lt;em&gt;p&lt;/em&gt;-value of the Chi-square test is also displayed at the bottom right.&lt;/p&gt;
&lt;p&gt;Moreover, this mosaic plot with colored cases shows where the observed frequencies deviates from the expected frequencies if the variables were independent. The red cases means that the observed frequencies are &lt;em&gt;smaller&lt;/em&gt; than the expected frequencies, whereas the blue cases means that the observed frequencies are &lt;em&gt;larger&lt;/em&gt; than the expected frequencies.&lt;/p&gt;
&lt;p&gt;An alternative is the &lt;code&gt;ggbarstats()&lt;/code&gt; function from the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load packages
library(ggstatsplot)
library(ggplot2)

# plot
ggbarstats(
  data = dat,
  x = size,
  y = Species
) +
  labs(caption = NULL) # remove caption&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r_files/figure-html/unnamed-chunk-11-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;From the plot, it seems that big flowers are more likely to belong to the &lt;code&gt;virginica&lt;/code&gt; species, while small flowers tend to belong to the &lt;code&gt;setosa&lt;/code&gt; species. Species and size are thus expected to be dependent.&lt;/p&gt;
&lt;p&gt;This is confirmed thanks to the statistical results displayed in the subtitle of the plot. There are several results, but we can in this case focus on the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value which is displayed after &lt;code&gt;p =&lt;/code&gt; at the top (in the subtitle of the plot).&lt;/p&gt;
&lt;p&gt;As with the previous tests, we reject the null hypothesis and we conclude that species and size are dependent (&lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &amp;lt; 0.001).&lt;/p&gt;
&lt;p&gt;Thanks for reading. I hope the article helped you to perform the Chi-square test of independence in R and interpret its results. If you would like to learn how to do this test by hand and how it works, read the article “&lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-by-hand/&#34;&gt;Chi-square test of independence by hand&lt;/a&gt;”. If you want to go further and &lt;em&gt;estimate&lt;/em&gt; the strength of the relationship between two categorical variables, see the &lt;a href=&#34;https://statsandr.com/blog/binary-logistic-regression-in-r/&#34;&gt;binary logistic regression&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;(Note that this article is available for download on my &lt;a href=&#34;https://statsandr.gumroad.com/&#34;&gt;Gumroad page&lt;/a&gt;.)&lt;/em&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;Thanks Herivelto for pointing it out.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Descriptive statistics in R</title>
      <link>https://statsandr.com/blog/descriptive-statistics-in-r/</link>
      <pubDate>Wed, 22 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/descriptive-statistics-in-r/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#data&#34; id=&#34;toc-data&#34;&gt;Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#minimum-and-maximum&#34; id=&#34;toc-minimum-and-maximum&#34;&gt;Minimum and maximum&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#range&#34; id=&#34;toc-range&#34;&gt;Range&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#mean&#34; id=&#34;toc-mean&#34;&gt;Mean&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#median&#34; id=&#34;toc-median&#34;&gt;Median&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#first-and-third-quartile&#34; id=&#34;toc-first-and-third-quartile&#34;&gt;First and third quartile&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#other-quantiles&#34; id=&#34;toc-other-quantiles&#34;&gt;Other quantiles&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#interquartile-range&#34; id=&#34;toc-interquartile-range&#34;&gt;Interquartile range&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#standard-deviation-and-variance&#34; id=&#34;toc-standard-deviation-and-variance&#34;&gt;Standard deviation and variance&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#summary&#34; id=&#34;toc-summary&#34;&gt;Summary&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#coefficient-of-variation&#34; id=&#34;toc-coefficient-of-variation&#34;&gt;Coefficient of variation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#mode&#34; id=&#34;toc-mode&#34;&gt;Mode&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#correlation&#34; id=&#34;toc-correlation&#34;&gt;Correlation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#contingency-table&#34; id=&#34;toc-contingency-table&#34;&gt;Contingency table&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#mosaic-plot&#34; id=&#34;toc-mosaic-plot&#34;&gt;Mosaic plot&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#barplot&#34; id=&#34;toc-barplot&#34;&gt;Barplot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#histogram&#34; id=&#34;toc-histogram&#34;&gt;Histogram&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#boxplot&#34; id=&#34;toc-boxplot&#34;&gt;Boxplot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#dotplot&#34; id=&#34;toc-dotplot&#34;&gt;Dotplot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scatterplot&#34; id=&#34;toc-scatterplot&#34;&gt;Scatterplot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#line-plot&#34; id=&#34;toc-line-plot&#34;&gt;Line plot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#qq-plot&#34; id=&#34;toc-qq-plot&#34;&gt;QQ-plot&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#for-a-single-variable&#34; id=&#34;toc-for-a-single-variable&#34;&gt;For a single variable&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#by-groups&#34; id=&#34;toc-by-groups&#34;&gt;By groups&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#density-plot&#34; id=&#34;toc-density-plot&#34;&gt;Density plot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#correlation-plot&#34; id=&#34;toc-correlation-plot&#34;&gt;Correlation plot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#advanced-descriptive-statistics&#34; id=&#34;toc-advanced-descriptive-statistics&#34;&gt;Advanced descriptive statistics&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#summarytools-package&#34; id=&#34;toc-summarytools-package&#34;&gt;&lt;code&gt;{summarytools}&lt;/code&gt; package&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#frequency-tables-with-freq&#34; id=&#34;toc-frequency-tables-with-freq&#34;&gt;Frequency tables with &lt;code&gt;freq()&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#cross-tabulations-with-ctable&#34; id=&#34;toc-cross-tabulations-with-ctable&#34;&gt;Cross-tabulations with &lt;code&gt;ctable()&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#descriptive-statistics-with-descr&#34; id=&#34;toc-descriptive-statistics-with-descr&#34;&gt;Descriptive statistics with &lt;code&gt;descr()&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#data-frame-summaries-with-dfsummary&#34; id=&#34;toc-data-frame-summaries-with-dfsummary&#34;&gt;Data frame summaries with &lt;code&gt;dfSummary()&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#describeby-from-the-psych-package&#34; id=&#34;toc-describeby-from-the-psych-package&#34;&gt;&lt;code&gt;describeBy()&lt;/code&gt; from the &lt;code&gt;{psych}&lt;/code&gt; package&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#aggregate-function&#34; id=&#34;toc-aggregate-function&#34;&gt;&lt;code&gt;aggregate()&lt;/code&gt; function&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#summaryby-from-doby&#34; id=&#34;toc-summaryby-from-doby&#34;&gt;&lt;code&gt;summaryBy()&lt;/code&gt; from &lt;code&gt;{doBy}&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#group_by-and-summarise-from-dplyr&#34; id=&#34;toc-group_by-and-summarise-from-dplyr&#34;&gt;&lt;code&gt;group_by()&lt;/code&gt; and &lt;code&gt;summarise()&lt;/code&gt; from &lt;code&gt;{dplyr}&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/descriptive-statistics-in-r.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;This article explains how to compute the main descriptive statistics in R and how to present them graphically. To learn more about the reasoning behind each descriptive statistics, how to compute them by hand and how to interpret them, read the article “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;Descriptive statistics by hand&lt;/a&gt;”.&lt;/p&gt;
&lt;p&gt;To briefly recap what have been said in that article, descriptive statistics (in the broad sense of the term) is a branch of statistics aiming at summarizing, describing and presenting a series of values or a dataset. Descriptive statistics is often the first step and an important part in any statistical analysis. It allows to check the quality of the data and it helps to “understand” the data by having a clear overview of it. If well presented, descriptive statistics is already a good starting point for further analyses. There exists many measures to summarize a dataset. They are divided into two types:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;location measures and&lt;/li&gt;
&lt;li&gt;dispersion measures&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Location measures give an understanding about the central tendency of the data, whereas dispersion measures give an understanding about the spread of the data. In this article, we focus only on the implementation in R of the most common descriptive statistics and their visualizations (when deemed appropriate). See online or in the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;above mentioned article&lt;/a&gt; for more information about the purpose and usage of each measure.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;data&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Data&lt;/h1&gt;
&lt;p&gt;We use the dataset &lt;code&gt;iris&lt;/code&gt; throughout the article. This dataset is imported by default in R, you only need to load it by running &lt;code&gt;iris&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- iris # load the iris dataset and renamed it dat&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Below a preview of this dataset and its structure:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;head(dat) # first 6 observations&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;str(dat) # structure of dataset&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## &amp;#39;data.frame&amp;#39;:	150 obs. of  5 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  $ Species     : Factor w/ 3 levels &amp;quot;setosa&amp;quot;,&amp;quot;versicolor&amp;quot;,..: 1 1 1 1 1 1 1 1 1 1 ...&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The dataset contains 150 observations and 5 variables, representing the length and width of the sepal and petal and the species of 150 flowers. Length and width of the sepal and petal are numeric variables and the species is a factor with 3 levels (indicated by &lt;code&gt;num&lt;/code&gt; and &lt;code&gt;Factor w/ 3 levels&lt;/code&gt; after the name of the variables). See the &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/&#34;&gt;different variables types in R&lt;/a&gt; if you need a refresh.&lt;/p&gt;
&lt;p&gt;Regarding plots, we present the default graphs and the graphs from the well-known &lt;code&gt;{ggplot2}&lt;/code&gt; package. Graphs from the &lt;code&gt;{ggplot2}&lt;/code&gt; package usually have a better look but it requires more advanced coding skills (see the article “&lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;Graphics in R with ggplot2&lt;/a&gt;” to learn more). If you need to publish or share your graphs, I suggest using &lt;code&gt;{ggplot2}&lt;/code&gt; if you can, otherwise the default graphics will do the job.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Tip:&lt;/em&gt; I recently discovered the ggplot2 builder from the &lt;code&gt;{esquisse}&lt;/code&gt; addins. See how you can easily &lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/&#34;&gt;draw graphs from the &lt;code&gt;{ggplot2}&lt;/code&gt; package&lt;/a&gt; without having to code it yourself.&lt;/p&gt;
&lt;p&gt;All plots displayed in this article can be customized. For instance, it is possible to edit the title, x and y-axis labels, color, etc. However, customizing plots is beyond the scope of this article so all plots are presented without any customization. Interested readers will find numerous resources online.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;minimum-and-maximum&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Minimum and maximum&lt;/h1&gt;
&lt;p&gt;Minimum and maximum can be found thanks to the &lt;code&gt;min()&lt;/code&gt; and &lt;code&gt;max()&lt;/code&gt; functions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;min(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 4.3&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;max(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 7.9&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Alternatively the &lt;code&gt;range()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rng &amp;lt;- range(dat$Sepal.Length)
rng&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 4.3 7.9&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;gives you the minimum and maximum directly. Note that the output of the &lt;code&gt;range()&lt;/code&gt; function is actually an object containing the minimum and maximum (in that order). This means you can actually access the minimum with:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rng[1] # rng = name of the object specified above&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 4.3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and the maximum with:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rng[2]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 7.9&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This reminds us that, in R, there are often several ways to arrive at the same result. The method that uses the shortest piece of code is usually preferred as a shorter piece of code is less prone to coding errors and more readable.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;range&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Range&lt;/h1&gt;
&lt;p&gt;The range can then be easily computed, as you have guessed, by subtracting the minimum from the maximum:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;max(dat$Sepal.Length) - min(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 3.6&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To my knowledge, there is no default function to compute the range. However, if you are familiar with writing functions in R
&lt;!-- (if not, see this article on [how to write a function in R](/blog/xxx/)) --&gt;
, you can create your own function to compute the range:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;range2 &amp;lt;- function(x) {
  range &amp;lt;- max(x) - min(x)
  return(range)
}

range2(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 3.6&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;which is equivalent than &lt;span class=&#34;math inline&#34;&gt;\(max - min\)&lt;/span&gt; presented above.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;mean&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Mean&lt;/h1&gt;
&lt;p&gt;The mean can be computed with the &lt;code&gt;mean()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mean(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 5.843333&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Tips:&lt;/em&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;if there is at least one missing value in your dataset, use &lt;code&gt;mean(dat$Sepal.Length, na.rm = TRUE)&lt;/code&gt; to compute the mean with the NA excluded. This argument can be used for most functions presented in this article, not only the mean&lt;/li&gt;
&lt;li&gt;for a truncated mean, use &lt;code&gt;mean(dat$Sepal.Length, trim = 0.10)&lt;/code&gt; and change the &lt;code&gt;trim&lt;/code&gt; argument to your needs&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;median&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Median&lt;/h1&gt;
&lt;p&gt;The median can be computed thanks to the &lt;code&gt;median()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;median(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 5.8&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or with the &lt;code&gt;quantile()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;quantile(dat$Sepal.Length, 0.5)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 50% 
## 5.8&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;since the quantile of order 0.5 (&lt;span class=&#34;math inline&#34;&gt;\(q_{0.5}\)&lt;/span&gt;) corresponds to the median.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;first-and-third-quartile&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;First and third quartile&lt;/h1&gt;
&lt;p&gt;As the median, the first and third quartiles can be computed thanks to the &lt;code&gt;quantile()&lt;/code&gt; function and by setting the second argument to 0.25 or 0.75:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;quantile(dat$Sepal.Length, 0.25) # first quartile&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 25% 
## 5.1&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;quantile(dat$Sepal.Length, 0.75) # third quartile&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 75% 
## 6.4&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You may have seen that the results above are slightly different than the results you would have found if you compute the first and third quartiles &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;by hand&lt;/a&gt;. It is normal, there are many methods to compute them (R actually has 7 methods to compute the quantiles!). However, the methods presented here and in the article “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics by hand&lt;/a&gt;” are the easiest and most “standard” ones. Furthermore, results do not dramatically change between the two methods.&lt;/p&gt;
&lt;div id=&#34;other-quantiles&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Other quantiles&lt;/h2&gt;
&lt;p&gt;As you have guessed, any quantile can also be computed with the &lt;code&gt;quantile()&lt;/code&gt; function. For instance, the &lt;span class=&#34;math inline&#34;&gt;\(4^{th}\)&lt;/span&gt; decile or the &lt;span class=&#34;math inline&#34;&gt;\(98^{th}\)&lt;/span&gt; percentile:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;quantile(dat$Sepal.Length, 0.4) # 4th decile&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 40% 
## 5.6&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;quantile(dat$Sepal.Length, 0.98) # 98th percentile&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 98% 
## 7.7&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;interquartile-range&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Interquartile range&lt;/h1&gt;
&lt;p&gt;The interquartile range (i.e., the difference between the first and third quartile) can be computed with the &lt;code&gt;IQR()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;IQR(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1.3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or alternatively with the &lt;code&gt;quantile()&lt;/code&gt; function again:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;quantile(dat$Sepal.Length, 0.75) - quantile(dat$Sepal.Length, 0.25)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 75% 
## 1.3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As mentioned earlier, when possible it is usually recommended to use the shortest piece of code to arrive at the result. For this reason, the &lt;code&gt;IQR()&lt;/code&gt; function is preferred to compute the interquartile range.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;standard-deviation-and-variance&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Standard deviation and variance&lt;/h1&gt;
&lt;p&gt;The standard deviation and the variance is computed with the &lt;code&gt;sd()&lt;/code&gt; and &lt;code&gt;var()&lt;/code&gt; functions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sd(dat$Sepal.Length) # standard deviation&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.8280661&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;var(dat$Sepal.Length) # variance&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.6856935&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Remember from the article &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics by hand&lt;/a&gt; that the standard deviation and the variance are different whether we compute it for a sample or a population (see the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;difference between sample and population&lt;/a&gt;). In R, the standard deviation and the variance are computed as if the data represent a sample (so the denominator is &lt;span class=&#34;math inline&#34;&gt;\(n - 1\)&lt;/span&gt;, where &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is the number of observations). To my knowledge, there is no function by default in R that computes the standard deviation or variance for a population.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Tip:&lt;/em&gt; to compute the standard deviation (or variance) of multiple variables at the same time, use &lt;code&gt;lapply()&lt;/code&gt; with the appropriate statistics as second argument:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;lapply(dat[, 1:4], sd)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $Sepal.Length
## [1] 0.8280661
## 
## $Sepal.Width
## [1] 0.4358663
## 
## $Petal.Length
## [1] 1.765298
## 
## $Petal.Width
## [1] 0.7622377&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The command &lt;code&gt;dat[, 1:4]&lt;/code&gt; selects the variables 1 to 4 as the fifth variable is a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;qualitative variable&lt;/a&gt; and the standard deviation cannot be computed on such type of variable. See a recap of the different &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/&#34;&gt;data types in R&lt;/a&gt; if needed.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;summary&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;You can compute the minimum, &lt;span class=&#34;math inline&#34;&gt;\(1^{st}\)&lt;/span&gt; quartile, median, mean, &lt;span class=&#34;math inline&#34;&gt;\(3^{rd}\)&lt;/span&gt; quartile and the maximum for all numeric variables of a dataset at once using &lt;code&gt;summary()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100  
##  1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300  
##  Median :5.800   Median :3.000   Median :4.350   Median :1.300  
##  Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199  
##  3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800  
##  Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500  
##        Species  
##  setosa    :50  
##  versicolor:50  
##  virginica :50  
##                 
##                 
## &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Tip:&lt;/em&gt; if you need these descriptive statistics by group use the &lt;code&gt;by()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;by(dat, dat$Species, summary)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## dat$Species: setosa
##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.300   Min.   :2.300   Min.   :1.000   Min.   :0.100  
##  1st Qu.:4.800   1st Qu.:3.200   1st Qu.:1.400   1st Qu.:0.200  
##  Median :5.000   Median :3.400   Median :1.500   Median :0.200  
##  Mean   :5.006   Mean   :3.428   Mean   :1.462   Mean   :0.246  
##  3rd Qu.:5.200   3rd Qu.:3.675   3rd Qu.:1.575   3rd Qu.:0.300  
##  Max.   :5.800   Max.   :4.400   Max.   :1.900   Max.   :0.600  
##        Species  
##  setosa    :50  
##  versicolor: 0  
##  virginica : 0  
##                 
##                 
##                 
## ------------------------------------------------------------ 
## dat$Species: versicolor
##   Sepal.Length    Sepal.Width     Petal.Length   Petal.Width          Species  
##  Min.   :4.900   Min.   :2.000   Min.   :3.00   Min.   :1.000   setosa    : 0  
##  1st Qu.:5.600   1st Qu.:2.525   1st Qu.:4.00   1st Qu.:1.200   versicolor:50  
##  Median :5.900   Median :2.800   Median :4.35   Median :1.300   virginica : 0  
##  Mean   :5.936   Mean   :2.770   Mean   :4.26   Mean   :1.326                  
##  3rd Qu.:6.300   3rd Qu.:3.000   3rd Qu.:4.60   3rd Qu.:1.500                  
##  Max.   :7.000   Max.   :3.400   Max.   :5.10   Max.   :1.800                  
## ------------------------------------------------------------ 
## dat$Species: virginica
##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.900   Min.   :2.200   Min.   :4.500   Min.   :1.400  
##  1st Qu.:6.225   1st Qu.:2.800   1st Qu.:5.100   1st Qu.:1.800  
##  Median :6.500   Median :3.000   Median :5.550   Median :2.000  
##  Mean   :6.588   Mean   :2.974   Mean   :5.552   Mean   :2.026  
##  3rd Qu.:6.900   3rd Qu.:3.175   3rd Qu.:5.875   3rd Qu.:2.300  
##  Max.   :7.900   Max.   :3.800   Max.   :6.900   Max.   :2.500  
##        Species  
##  setosa    : 0  
##  versicolor: 0  
##  virginica :50  
##                 
##                 
## &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;where the arguments are the name of the dataset, the grouping variable and the summary function. Follow this order, or specify the name of the arguments if you do not follow this order.&lt;/p&gt;
&lt;p&gt;If you need more descriptive statistics, use &lt;code&gt;stat.desc()&lt;/code&gt; from the package &lt;code&gt;{pastecs}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(pastecs)
stat.desc(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##              Sepal.Length  Sepal.Width Petal.Length  Petal.Width Species
## nbr.val      150.00000000 150.00000000  150.0000000 150.00000000      NA
## nbr.null       0.00000000   0.00000000    0.0000000   0.00000000      NA
## nbr.na         0.00000000   0.00000000    0.0000000   0.00000000      NA
## min            4.30000000   2.00000000    1.0000000   0.10000000      NA
## max            7.90000000   4.40000000    6.9000000   2.50000000      NA
## range          3.60000000   2.40000000    5.9000000   2.40000000      NA
## sum          876.50000000 458.60000000  563.7000000 179.90000000      NA
## median         5.80000000   3.00000000    4.3500000   1.30000000      NA
## mean           5.84333333   3.05733333    3.7580000   1.19933333      NA
## SE.mean        0.06761132   0.03558833    0.1441360   0.06223645      NA
## CI.mean.0.95   0.13360085   0.07032302    0.2848146   0.12298004      NA
## var            0.68569351   0.18997942    3.1162779   0.58100626      NA
## std.dev        0.82806613   0.43586628    1.7652982   0.76223767      NA
## coef.var       0.14171126   0.14256420    0.4697441   0.63555114      NA&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can have even more statistics (i.e., skewness, kurtosis and &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normality test&lt;/a&gt;) by adding the argument &lt;code&gt;norm = TRUE&lt;/code&gt; in the previous function. Note that the variable &lt;code&gt;Species&lt;/code&gt; is not numeric, so descriptive statistics cannot be computed for this variable and NA are displayed.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;coefficient-of-variation&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Coefficient of variation&lt;/h1&gt;
&lt;p&gt;The coefficient of variation can be found with &lt;code&gt;stat.desc()&lt;/code&gt; (see the line &lt;code&gt;coef.var&lt;/code&gt; in the table above) or by computing manually (remember that the coefficient of variation is the standard deviation divided by the mean):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sd(dat$Sepal.Length) / mean(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.1417113&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;mode&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Mode&lt;/h1&gt;
&lt;p&gt;To my knowledge there is no function to find the mode of a variable. However, we can easily find it thanks to the functions &lt;code&gt;table()&lt;/code&gt; and &lt;code&gt;sort()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;tab &amp;lt;- table(dat$Sepal.Length) # number of occurrences for each unique value
sort(tab, decreasing = TRUE) # sort highest to lowest&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##   5 5.1 6.3 5.7 6.7 5.5 5.8 6.4 4.9 5.4 5.6   6 6.1 4.8 6.5 4.6 5.2 6.2 6.9 7.7 
##  10   9   9   8   8   7   7   7   6   6   6   6   6   5   5   4   4   4   4   4 
## 4.4 5.9 6.8 7.2 4.7 6.6 4.3 4.5 5.3   7 7.1 7.3 7.4 7.6 7.9 
##   3   3   3   3   2   2   1   1   1   1   1   1   1   1   1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;table()&lt;/code&gt; gives the number of occurrences for each unique value, then &lt;code&gt;sort()&lt;/code&gt; with the argument &lt;code&gt;decreasing = TRUE&lt;/code&gt; displays the number of occurrences from highest to lowest. The mode of the variable &lt;code&gt;Sepal.Length&lt;/code&gt; is thus 5. This code to find the mode can also be applied to qualitative variables such as &lt;code&gt;Species&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sort(table(dat$Species), decreasing = TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##     setosa versicolor  virginica 
##         50         50         50&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(dat$Species)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##     setosa versicolor  virginica 
##         50         50         50&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;correlation&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Correlation&lt;/h1&gt;
&lt;p&gt;Another descriptive statistics is the correlation coefficient.&lt;/p&gt;
&lt;p&gt;The correlation measures the &lt;em&gt;linear&lt;/em&gt; relationship between two variables, and it can be computed with the &lt;code&gt;cor()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;cor(dat$Sepal.Length, dat$Sepal.Width)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] -0.1175698&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Computing correlation in R and interpreting the results deserve a detailed explanation, so I wrote an article covering &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;correlation and correlation test&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;contingency-table&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Contingency table&lt;/h1&gt;
&lt;p&gt;&lt;code&gt;table()&lt;/code&gt; introduced above can also be used on two qualitative variables to create a contingency table. The dataset &lt;code&gt;iris&lt;/code&gt; has only one qualitative variable so we create a new qualitative variable just for this example. We create the variable &lt;code&gt;size&lt;/code&gt; which corresponds to &lt;code&gt;small&lt;/code&gt; if the length of the petal is smaller than the median of all flowers, &lt;code&gt;big&lt;/code&gt; otherwise:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat$size &amp;lt;- ifelse(dat$Sepal.Length &amp;lt; median(dat$Sepal.Length),
  &amp;quot;small&amp;quot;, &amp;quot;big&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here is a recap of the occurrences by size:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;table(dat$size)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##   big small 
##    77    73&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We now create a contingency table of the two variables &lt;code&gt;Species&lt;/code&gt; and &lt;code&gt;size&lt;/code&gt; with the &lt;code&gt;table()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;table(dat$Species, dat$size)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             
##              big small
##   setosa       1    49
##   versicolor  29    21
##   virginica   47     3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or with the &lt;code&gt;xtabs()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;xtabs(~ dat$Species + dat$size)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             dat$size
## dat$Species  big small
##   setosa       1    49
##   versicolor  29    21
##   virginica   47     3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The contingency table gives the number of cases in each subgroup. For instance, there is only one big setosa flower, while there are 49 small setosa flowers in the dataset.&lt;/p&gt;
&lt;p&gt;To go further, we can see from the table that setosa flowers seem to be smaller in size than virginica flowers. In order to check whether size is significantly associated with species, we could perform a Chi-square test of independence since both variables are categorical variables. See how to do this test &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-by-hand/&#34;&gt;by hand&lt;/a&gt; and &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;in R&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Note that &lt;code&gt;Species&lt;/code&gt; are in rows and &lt;code&gt;size&lt;/code&gt; in column because we specified &lt;code&gt;Species&lt;/code&gt; and then &lt;code&gt;size&lt;/code&gt; in &lt;code&gt;table()&lt;/code&gt;. Change the order if you want to switch the two variables.&lt;/p&gt;
&lt;p&gt;Instead of having the frequencies (i.e.. the number of cases) you can also have the relative frequencies (i.e., proportions) in each subgroup by adding the &lt;code&gt;table()&lt;/code&gt; function inside the &lt;code&gt;prop.table()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;prop.table(table(dat$Species, dat$size))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             
##                      big       small
##   setosa     0.006666667 0.326666667
##   versicolor 0.193333333 0.140000000
##   virginica  0.313333333 0.020000000&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that you can also compute the percentages by row or by column by adding a second argument to the &lt;code&gt;prop.table()&lt;/code&gt; function: &lt;code&gt;1&lt;/code&gt; for row, or &lt;code&gt;2&lt;/code&gt; for column:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# percentages by row:
round(prop.table(table(dat$Species, dat$size), 1), 2) # round to 2 digits with round()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             
##               big small
##   setosa     0.02  0.98
##   versicolor 0.58  0.42
##   virginica  0.94  0.06&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# percentages by column:
round(prop.table(table(dat$Species, dat$size), 2), 2) # round to 2 digits with round()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             
##               big small
##   setosa     0.01  0.67
##   versicolor 0.38  0.29
##   virginica  0.61  0.04&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;See the section on &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#cross-tabulations-with-ctable&#34;&gt;advanced descriptive statistics&lt;/a&gt; for more advanced contingency tables.&lt;/p&gt;
&lt;div id=&#34;mosaic-plot&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Mosaic plot&lt;/h2&gt;
&lt;p&gt;A mosaic plot allows to visualize a contingency table of two qualitative variables:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mosaicplot(table(dat$Species, dat$size),
  color = TRUE,
  xlab = &amp;quot;Species&amp;quot;, # label for x-axis
  ylab = &amp;quot;Size&amp;quot; # label for y-axis
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-32-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The mosaic plot shows that, for our sample, the proportion of big and small flowers is clearly different between the three species. In particular, the virginica species is the biggest, and the setosa species is the smallest of the three species (in terms of sepal length since the variable &lt;code&gt;size&lt;/code&gt; is based on the variable &lt;code&gt;Sepal.Length&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;For your information, a mosaic plot can also be done via the &lt;code&gt;mosaic()&lt;/code&gt; function from the &lt;code&gt;{vcd}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(vcd)

mosaic(~ Species + size,
  data = dat,
  direction = c(&amp;quot;v&amp;quot;, &amp;quot;h&amp;quot;)
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-33-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;barplot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Barplot&lt;/h1&gt;
&lt;p&gt;Barplots can only be done on qualitative variables (see the difference with a quantitative variable &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/&#34;&gt;here&lt;/a&gt;). A barplot is a tool to visualize the distribution of a qualitative variable. We draw a barplot of the qualitative variable &lt;code&gt;size&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;barplot(table(dat$size)) # table() is mandatory&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-34-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;You can also draw a barplot of the relative frequencies instead of the frequencies by adding &lt;code&gt;prop.table()&lt;/code&gt; as we did earlier:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;barplot(prop.table(table(dat$size)))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-35-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggplot2) # needed each time you open RStudio
# The package ggplot2 must be installed first

ggplot(dat) +
  aes(x = size) +
  geom_bar()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-36-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;histogram&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Histogram&lt;/h1&gt;
&lt;p&gt;A histogram gives an idea about the distribution of a quantitative variable. The idea is to break the range of values into intervals and count how many observations fall into each interval. Histograms are a bit similar to barplots, but histograms are used for quantitative variables whereas barplots are used for qualitative variables. To draw a histogram in R, use &lt;code&gt;hist()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;hist(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-37-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Add the arguments &lt;code&gt;breaks =&lt;/code&gt; inside the &lt;code&gt;hist()&lt;/code&gt; function if you want to change the number of bins. A rule of thumb (known as the square-root rule) is that the number of bins should be the rounded value of the square root of the number of observations. The dataset includes 150 observations so in this case the number of bins can be set to 12.&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Sepal.Length) +
  geom_histogram()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-38-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;By default, the number of bins is 30. You can change this value with &lt;code&gt;geom_histogram(bins = 12)&lt;/code&gt; for instance.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;boxplot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Boxplot&lt;/h1&gt;
&lt;p&gt;Boxplots are really useful in descriptive statistics and are often underused (mostly because it is not well understood by the public). A boxplot graphically represents the distribution of a quantitative variable by visually displaying five common location summary (minimum, median, first/third quartiles and maximum) and any observation that was classified as a suspected &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outlier&lt;/a&gt; using the interquartile range (IQR) criterion.&lt;/p&gt;
&lt;p&gt;The IQR criterion means that all observations above &lt;span class=&#34;math inline&#34;&gt;\(q_{0.75} + 1.5 \cdot IQR\)&lt;/span&gt; or below &lt;span class=&#34;math inline&#34;&gt;\(q_{0.25} - 1.5 \cdot IQR\)&lt;/span&gt; (where &lt;span class=&#34;math inline&#34;&gt;\(q_{0.25}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(q_{0.75}\)&lt;/span&gt; correspond to first and third quartile respectively) are considered as potential outliers by R. The minimum and maximum in the boxplot are represented without these suspected outliers.&lt;/p&gt;
&lt;p&gt;Seeing all these information on the same plot help to have a good first overview of the dispersion and the location of the data. Before drawing a boxplot of our data, see below a graph explaining the information present on a boxplot:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/how-to-interpret-boxplot.png&#34; style=&#34;width:100.0%&#34; alt=&#34;How to interpret a boxplot? Source: LFSAB1105&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;How to interpret a boxplot? Source: LFSAB1105&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;Now an example with our dataset:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;boxplot(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-39-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Boxplots are even more informative when presented side-by-side for comparing and contrasting distributions from two or more groups. For instance, we compare the length of the sepal across the different species:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;boxplot(dat$Sepal.Length ~ dat$Species)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-40-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Species, y = Sepal.Length) +
  geom_boxplot()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-41-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;dotplot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Dotplot&lt;/h1&gt;
&lt;p&gt;A dotplot is more or less similar than a boxplot, except that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;observations are represented as points&lt;/li&gt;
&lt;li&gt;it does not easily tell us about the median, first and third quartiles.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(lattice)

dotplot(dat$Sepal.Length ~ dat$Species)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-42-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Species, y = Sepal.Length) +
  geom_dotplot(binaxis = &amp;quot;y&amp;quot;, stackdir = &amp;quot;center&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-43-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The advantage of using &lt;code&gt;{ggplot2}&lt;/code&gt; over &lt;code&gt;{lattice}&lt;/code&gt; for this plot is that we can easily see the mode.&lt;/p&gt;
&lt;p&gt;Note that a dotplot is particularly useful when there are a limited number of observations, whereas a boxplot is more appropriate with large datasets.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;scatterplot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Scatterplot&lt;/h1&gt;
&lt;p&gt;Scatterplots allow to check whether there is a potential link between two quantitative variables. For this reason, scatterplots are often used to visualize a potential &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;correlation&lt;/a&gt; between two variables. For instance, when drawing a scatterplot of the length of the sepal and the length of the petal:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(dat$Sepal.Length, dat$Petal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-44-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;There seems to be a positive association between the two variables.&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Sepal.Length, y = Petal.Length) +
  geom_point()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-45-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Like boxplots, scatterplots are even more informative when differentiating the points according to a factor, in this case the species:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Sepal.Length, y = Petal.Length, colour = Species) +
  geom_point() +
  scale_color_hue()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-46-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;line-plot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Line plot&lt;/h1&gt;
&lt;p&gt;Line plots, particularly useful in time series or finance, can be created by adding the &lt;code&gt;type = &#34;l&#34;&lt;/code&gt; argument in the &lt;code&gt;plot()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(dat$Sepal.Length,
  type = &amp;quot;l&amp;quot;
) # &amp;quot;l&amp;quot; for line&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-47-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;qq-plot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;QQ-plot&lt;/h1&gt;
&lt;div id=&#34;for-a-single-variable&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;For a single variable&lt;/h2&gt;
&lt;p&gt;In order to check the normality assumption of a variable (normality means that the data follow a normal distribution, also known as a Gaussian distribution), we usually use histograms and/or QQ-plots.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; See an article discussing about the &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution and how to evaluate the normality assumption in R&lt;/a&gt; if you need a refresh on that subject.&lt;/p&gt;
&lt;p&gt;Histograms have been presented earlier, so here is how to draw a QQ-plot:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Draw points on the qq-plot:
qqnorm(dat$Sepal.Length)
# Draw the reference line:
qqline(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-48-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Or a QQ-plot with confidence bands with the &lt;code&gt;qqPlot()&lt;/code&gt; function from the &lt;code&gt;{car}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(car) # package must be installed first
qqPlot(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-49-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## [1] 132 118&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If points are close to the reference line (sometimes referred as Henry’s line) and within the confidence bands, the normality assumption can be considered as met. The bigger the deviation between the points and the reference line and the more they lie outside the confidence bands, the less likely that the normality condition is met. The variable &lt;code&gt;Sepal.Length&lt;/code&gt; does not seem to follow a normal distribution because several points lie outside the confidence bands. When facing a non-normal distribution, the first step is usually to apply the logarithm transformation on the data and recheck to see whether the log-transformed data are normally distributed. Applying the logarithm transformation can be done with the &lt;code&gt;log()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggpubr}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggpubr)
ggqqplot(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-50-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;by-groups&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;By groups&lt;/h2&gt;
&lt;p&gt;For some &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt;, the normality assumption is required in all groups. One solution is to draw a QQ-plot for each group by manually splitting the dataset into different groups and then draw a QQ-plot for each subset of the data (with the methods shown above). Another (easier) solution is to draw a QQ-plot for each group automatically with the argument &lt;code&gt;groups =&lt;/code&gt; in the function &lt;code&gt;qqPlot()&lt;/code&gt; from the &lt;code&gt;{car}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;qqPlot(dat$Sepal.Length, groups = dat$size)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-51-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;qplot(
  sample = Sepal.Length, data = dat,
  col = size, shape = size
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-52-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;It is also possible to differentiate groups by only shape or color. For this, remove one of the argument &lt;code&gt;col&lt;/code&gt; or &lt;code&gt;shape&lt;/code&gt; in the &lt;code&gt;qplot()&lt;/code&gt; function above.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;density-plot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Density plot&lt;/h1&gt;
&lt;p&gt;Density plot is a smoothed version of the histogram and is used in the same concept, that is, to represent the distribution of a numeric variable. The functions &lt;code&gt;plot()&lt;/code&gt; and &lt;code&gt;density()&lt;/code&gt; are used together to draw a density plot:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(density(dat$Sepal.Length))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-53-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Sepal.Length) +
  geom_density()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-54-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;correlation-plot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Correlation plot&lt;/h1&gt;
&lt;p&gt;The last type of descriptive plot is a correlation plot, also called a correlogram. This type of graph is more complex than the ones presented above, so it is detailed in a separate article. See &lt;a href=&#34;https://statsandr.com/blog/correlogram-in-r-how-to-highlight-the-most-correlated-variables-in-a-dataset/&#34;&gt;how to draw a correlogram to highlight the most correlated variables in a dataset&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;advanced-descriptive-statistics&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Advanced descriptive statistics&lt;/h1&gt;
&lt;p&gt;We covered the main functions to compute the most common and basic descriptive statistics. There are, however, many more functions and packages to perform more advanced descriptive statistics in R. In this section, I present some of them with applications to our dataset.&lt;/p&gt;
&lt;div id=&#34;summarytools-package&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;&lt;code&gt;{summarytools}&lt;/code&gt; package&lt;/h2&gt;
&lt;p&gt;One package for descriptive statistics I often use for my projects in R is the &lt;a href=&#34;https://cran.r-project.org/web/packages/summarytools/index.html&#34; target=&#34;_blank&#34;&gt;&lt;code&gt;{summarytools}&lt;/code&gt;&lt;/a&gt; package. The package is centered around 4 functions:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;code&gt;freq()&lt;/code&gt; for frequencies tables&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ctable()&lt;/code&gt; for cross-tabulations&lt;/li&gt;
&lt;li&gt;&lt;code&gt;descr()&lt;/code&gt; for descriptive statistics&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfSummary()&lt;/code&gt; for dataframe summaries&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;A combination of these 4 functions is usually more than enough for most descriptive analyses. Moreover, the package has been built with &lt;a href=&#34;https://statsandr.com/blog/getting-started-in-r-markdown/&#34;&gt;R Markdown&lt;/a&gt; in mind, meaning that outputs render well in HTML reports. And for non-English speakers, built-in translations exist for French, Portuguese, Spanish, Russian and Turkish.&lt;/p&gt;
&lt;p&gt;I illustrate each of the 4 functions in the following sections. Outputs that follow display much better in R Markdown reports, but in this article I limit myself to the raw outputs as the goal is to show how the functions work, not how to make them render well. See the setup settings in the &lt;a href=&#34;https://cran.r-project.org/web/packages/summarytools/vignettes/introduction.html&#34; target=&#34;_blank&#34;&gt;vignette&lt;/a&gt; of the package if you want to print the outputs in a nice way in R Markdown.&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;div id=&#34;frequency-tables-with-freq&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Frequency tables with &lt;code&gt;freq()&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;freq()&lt;/code&gt; function produces frequency tables with frequencies, proportions, as well as missing data information.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(summarytools)
freq(dat$Species)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Frequencies  
## dat$Species  
## Type: Factor  
## 
##                    Freq   % Valid   % Valid Cum.   % Total   % Total Cum.
## ---------------- ------ --------- -------------- --------- --------------
##           setosa     50     33.33          33.33     33.33          33.33
##       versicolor     50     33.33          66.67     33.33          66.67
##        virginica     50     33.33         100.00     33.33         100.00
##             &amp;lt;NA&amp;gt;      0                               0.00         100.00
##            Total    150    100.00         100.00    100.00         100.00&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you do not need information about missing values, add the &lt;code&gt;report.nas = FALSE&lt;/code&gt; argument:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;freq(dat$Species,
  report.nas = FALSE # remove NA information
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Frequencies  
## dat$Species  
## Type: Factor  
## 
##                    Freq        %   % Cum.
## ---------------- ------ -------- --------
##           setosa     50    33.33    33.33
##       versicolor     50    33.33    66.67
##        virginica     50    33.33   100.00
##            Total    150   100.00   100.00&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And for a minimalist output with only counts and proportions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;freq(dat$Species,
  report.nas = FALSE, # remove NA information
  totals = FALSE, # remove totals
  cumul = FALSE, # remove cumuls
  headings = FALSE # remove headings
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##                    Freq       %
## ---------------- ------ -------
##           setosa     50   33.33
##       versicolor     50   33.33
##        virginica     50   33.33&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;cross-tabulations-with-ctable&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Cross-tabulations with &lt;code&gt;ctable()&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;ctable()&lt;/code&gt; function produces cross-tabulations (also known as contingency tables) for pairs of categorical variables. Using the two categorical variables in our dataset:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ctable(
  x = dat$Species,
  y = dat$size
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Cross-Tabulation, Row Proportions  
## Species * size  
## Data Frame: dat  
## 
## ------------ ------ ------------ ------------ --------------
##                size          big        small          Total
##      Species                                                
##       setosa           1 ( 2.0%)   49 (98.0%)    50 (100.0%)
##   versicolor          29 (58.0%)   21 (42.0%)    50 (100.0%)
##    virginica          47 (94.0%)    3 ( 6.0%)    50 (100.0%)
##        Total          77 (51.3%)   73 (48.7%)   150 (100.0%)
## ------------ ------ ------------ ------------ --------------&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Row proportions are shown by default. To display column or total proportions, add the &lt;code&gt;prop = &#34;c&#34;&lt;/code&gt; or &lt;code&gt;prop = &#34;t&#34;&lt;/code&gt; arguments, respectively:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ctable(
  x = dat$Species,
  y = dat$size,
  prop = &amp;quot;t&amp;quot; # total proportions
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Cross-Tabulation, Total Proportions  
## Species * size  
## Data Frame: dat  
## 
## ------------ ------ ------------ ------------ --------------
##                size          big        small          Total
##      Species                                                
##       setosa           1 ( 0.7%)   49 (32.7%)    50 ( 33.3%)
##   versicolor          29 (19.3%)   21 (14.0%)    50 ( 33.3%)
##    virginica          47 (31.3%)    3 ( 2.0%)    50 ( 33.3%)
##        Total          77 (51.3%)   73 (48.7%)   150 (100.0%)
## ------------ ------ ------------ ------------ --------------&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To remove proportions altogether, add the argument &lt;code&gt;prop = &#34;n&#34;&lt;/code&gt;. Furthermore, to display only the bare minimum, add the &lt;code&gt;totals = FALSE&lt;/code&gt; and &lt;code&gt;headings = FALSE&lt;/code&gt; arguments:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ctable(
  x = dat$Species,
  y = dat$size,
  prop = &amp;quot;n&amp;quot;, # remove proportions
  totals = FALSE, # remove totals
  headings = FALSE # remove headings
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## ------------ ------ ----- -------
##                size   big   small
##      Species                     
##       setosa            1      49
##   versicolor           29      21
##    virginica           47       3
## ------------ ------ ----- -------&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is equivalent than &lt;code&gt;table(dat$Species, dat$size)&lt;/code&gt; and &lt;code&gt;xtabs(~ dat$Species + dat$size)&lt;/code&gt; performed in the section on &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#contingency-table&#34;&gt;contingency tables&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;To display results of the &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;Chi-square test of independence&lt;/a&gt;, add the &lt;code&gt;chisq = TRUE&lt;/code&gt; argument:&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ctable(
  x = dat$Species,
  y = dat$size,
  chisq = TRUE, # display results of Chi-square test of independence
  headings = FALSE # remove headings
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## ------------ ------ ------------ ------------ --------------
##                size          big        small          Total
##      Species                                                
##       setosa           1 ( 2.0%)   49 (98.0%)    50 (100.0%)
##   versicolor          29 (58.0%)   21 (42.0%)    50 (100.0%)
##    virginica          47 (94.0%)    3 ( 6.0%)    50 (100.0%)
##        Total          77 (51.3%)   73 (48.7%)   150 (100.0%)
## ------------ ------ ------------ ------------ --------------
## 
## ----------------------------
##  Chi.squared   df   p.value 
## ------------- ---- ---------
##    86.0345     2       0    
## ----------------------------&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is close to 0 so we reject the null hypothesis of independence between the two variables. In our context, this indicates that species and size are dependent and that there is a significant relationship between the two variables.&lt;/p&gt;
&lt;p&gt;It is also possible to create a contingency table for each level of a third categorical variable thanks to the combination of the &lt;code&gt;stby()&lt;/code&gt; and &lt;code&gt;ctable()&lt;/code&gt; functions. There are only 2 categorical variables in our dataset, so let’s use the &lt;code&gt;tabacco&lt;/code&gt; dataset which has 4 categorical variables (i.e., gender, age group, smoker, diseased). For this example, we would like to create a contingency table of the variables &lt;code&gt;smoker&lt;/code&gt; and &lt;code&gt;diseased&lt;/code&gt;, and this for each &lt;code&gt;gender&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;stby(
  list(
    x = tobacco$smoker, # smoker and diseased
    y = tobacco$diseased
  ),
  INDICES = tobacco$gender, # for each gender
  FUN = ctable # ctable for cross-tabulation
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Cross-Tabulation, Row Proportions  
## smoker * diseased  
## Data Frame: tobacco  
## Group: gender = F  
## 
## -------- ---------- ------------- ------------- --------------
##            diseased           Yes            No          Total
##   smoker                                                      
##      Yes               62 (42.2%)    85 (57.8%)   147 (100.0%)
##       No               49 (14.3%)   293 (85.7%)   342 (100.0%)
##    Total              111 (22.7%)   378 (77.3%)   489 (100.0%)
## -------- ---------- ------------- ------------- --------------
## 
## Group: gender = M  
## 
## -------- ---------- ------------- ------------- --------------
##            diseased           Yes            No          Total
##   smoker                                                      
##      Yes               63 (44.1%)    80 (55.9%)   143 (100.0%)
##       No               47 (13.6%)   299 (86.4%)   346 (100.0%)
##    Total              110 (22.5%)   379 (77.5%)   489 (100.0%)
## -------- ---------- ------------- ------------- --------------&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;descriptive-statistics-with-descr&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Descriptive statistics with &lt;code&gt;descr()&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;descr()&lt;/code&gt; function produces descriptive (univariate) statistics with common central tendency statistics and measures of dispersion. (See the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#location-versus-dispersion-measures&#34;&gt;difference between a measure of central tendency and dispersion&lt;/a&gt; if you need a reminder.)&lt;/p&gt;
&lt;p&gt;A major advantage of this function is that it accepts single vectors as well as data frames. If a data frame is provided, all non-numerical columns are ignored so you do not have to remove them yourself before running the function.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;descr()&lt;/code&gt; function allows to display:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;only a selection of descriptive statistics of your choice, with the &lt;code&gt;stats = c(&#34;mean&#34;, &#34;sd&#34;)&lt;/code&gt; argument for mean and standard deviation for example&lt;/li&gt;
&lt;li&gt;the minimum, first quartile, median, third quartile and maximum with &lt;code&gt;stats = &#34;fivenum&#34;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;the most common descriptive statistics (mean, standard deviation, minimum, median, maximum, number and percentage of valid observations), with &lt;code&gt;stats = &#34;common&#34;&lt;/code&gt;:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;descr(dat,
  headings = FALSE, # remove headings
  stats = &amp;quot;common&amp;quot; # most common descriptive statistics
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##                   Petal.Length   Petal.Width   Sepal.Length   Sepal.Width
## --------------- -------------- ------------- -------------- -------------
##            Mean           3.76          1.20           5.84          3.06
##         Std.Dev           1.77          0.76           0.83          0.44
##             Min           1.00          0.10           4.30          2.00
##          Median           4.35          1.30           5.80          3.00
##             Max           6.90          2.50           7.90          4.40
##         N.Valid         150.00        150.00         150.00        150.00
##               N         150.00        150.00         150.00        150.00
##       Pct.Valid         100.00        100.00         100.00        100.00&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Tip:&lt;/em&gt; if you have a large number of variables, add the &lt;code&gt;transpose = TRUE&lt;/code&gt; argument for a better display.&lt;/p&gt;
&lt;p&gt;In order to compute these descriptive statistics by group (e.g., &lt;code&gt;Species&lt;/code&gt; in our dataset), use the &lt;code&gt;descr()&lt;/code&gt; function in combination with the &lt;code&gt;stby()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;stby(
  data = dat,
  INDICES = dat$Species, # by Species
  FUN = descr, # descriptive statistics
  stats = &amp;quot;common&amp;quot; # most common descr. stats
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Descriptive Statistics  
## dat  
## Group: Species = setosa  
## N: 50  
## 
##                   Petal.Length   Petal.Width   Sepal.Length   Sepal.Width
## --------------- -------------- ------------- -------------- -------------
##            Mean           1.46          0.25           5.01          3.43
##         Std.Dev           0.17          0.11           0.35          0.38
##             Min           1.00          0.10           4.30          2.30
##          Median           1.50          0.20           5.00          3.40
##             Max           1.90          0.60           5.80          4.40
##         N.Valid          50.00         50.00          50.00         50.00
##               N          50.00         50.00          50.00         50.00
##       Pct.Valid         100.00        100.00         100.00        100.00
## 
## Group: Species = versicolor  
## N: 50  
## 
##                   Petal.Length   Petal.Width   Sepal.Length   Sepal.Width
## --------------- -------------- ------------- -------------- -------------
##            Mean           4.26          1.33           5.94          2.77
##         Std.Dev           0.47          0.20           0.52          0.31
##             Min           3.00          1.00           4.90          2.00
##          Median           4.35          1.30           5.90          2.80
##             Max           5.10          1.80           7.00          3.40
##         N.Valid          50.00         50.00          50.00         50.00
##               N          50.00         50.00          50.00         50.00
##       Pct.Valid         100.00        100.00         100.00        100.00
## 
## Group: Species = virginica  
## N: 50  
## 
##                   Petal.Length   Petal.Width   Sepal.Length   Sepal.Width
## --------------- -------------- ------------- -------------- -------------
##            Mean           5.55          2.03           6.59          2.97
##         Std.Dev           0.55          0.27           0.64          0.32
##             Min           4.50          1.40           4.90          2.20
##          Median           5.55          2.00           6.50          3.00
##             Max           6.90          2.50           7.90          3.80
##         N.Valid          50.00         50.00          50.00         50.00
##               N          50.00         50.00          50.00         50.00
##       Pct.Valid         100.00        100.00         100.00        100.00&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;data-frame-summaries-with-dfsummary&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Data frame summaries with &lt;code&gt;dfSummary()&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;dfSummary()&lt;/code&gt; function generates a summary table with statistics, frequencies and graphs for all variables in a dataset. The information shown depends on the type of the variables (character, factor, numeric, date) and also varies according to the number of distinct values.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dfSummary(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Data Frame Summary  
## dat  
## Dimensions: 150 x 6  
## Duplicates: 1  
## 
## -----------------------------------------------------------------------------------------------------------
## No   Variable       Stats / Values          Freqs (% of Valid)   Graph                 Valid      Missing  
## ---- -------------- ----------------------- -------------------- --------------------- ---------- ---------
## 1    Sepal.Length   Mean (sd) : 5.8 (0.8)   35 distinct values     . . : :             150        0        
##      [numeric]      min &amp;lt; med &amp;lt; max:                               : : : :             (100.0%)   (0.0%)   
##                     4.3 &amp;lt; 5.8 &amp;lt; 7.9                                : : : : :                               
##                     IQR (CV) : 1.3 (0.1)                           : : : : :                               
##                                                                  : : : : : : : :                           
## 
## 2    Sepal.Width    Mean (sd) : 3.1 (0.4)   23 distinct values           :             150        0        
##      [numeric]      min &amp;lt; med &amp;lt; max:                                     :             (100.0%)   (0.0%)   
##                     2 &amp;lt; 3 &amp;lt; 4.4                                        . :                                 
##                     IQR (CV) : 0.5 (0.1)                             : : : :                               
##                                                                  . . : : : : : :                           
## 
## 3    Petal.Length   Mean (sd) : 3.8 (1.8)   43 distinct values   :                     150        0        
##      [numeric]      min &amp;lt; med &amp;lt; max:                             :         . :         (100.0%)   (0.0%)   
##                     1 &amp;lt; 4.3 &amp;lt; 6.9                                :         : : .                           
##                     IQR (CV) : 3.5 (0.5)                         : :       : : : .                         
##                                                                  : :   . : : : : : .                       
## 
## 4    Petal.Width    Mean (sd) : 1.2 (0.8)   22 distinct values   :                     150        0        
##      [numeric]      min &amp;lt; med &amp;lt; max:                             :                     (100.0%)   (0.0%)   
##                     0.1 &amp;lt; 1.3 &amp;lt; 2.5                              :       . .   :                           
##                     IQR (CV) : 1.5 (0.6)                         :       : :   :   .                       
##                                                                  : :   : : : . : : :                       
## 
## 5    Species        1. setosa               50 (33.3%)           IIIIII                150        0        
##      [factor]       2. versicolor           50 (33.3%)           IIIIII                (100.0%)   (0.0%)   
##                     3. virginica            50 (33.3%)           IIIIII                                    
## 
## 6    size           1. big                  77 (51.3%)           IIIIIIIIII            150        0        
##      [character]    2. small                73 (48.7%)           IIIIIIIII             (100.0%)   (0.0%)   
## -----------------------------------------------------------------------------------------------------------&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;describeby-from-the-psych-package&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;&lt;code&gt;describeBy()&lt;/code&gt; from the &lt;code&gt;{psych}&lt;/code&gt; package&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;describeBy()&lt;/code&gt; function from the &lt;code&gt;{psych}&lt;/code&gt; package allows to report several summary statistics (i.e., number of valid cases, mean, standard deviation, median, trimmed mean, mad: median absolute deviation (from the median), minimum, maximum, range, skewness and kurtosis) by a grouping variable.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(psych)
describeBy(
  dat,
  dat$Species # grouping variable
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Descriptive statistics by group 
## group: setosa
##              vars  n mean   sd median trimmed  mad min max range  skew kurtosis
## Sepal.Length    1 50 5.01 0.35    5.0    5.00 0.30 4.3 5.8   1.5  0.11    -0.45
## Sepal.Width     2 50 3.43 0.38    3.4    3.42 0.37 2.3 4.4   2.1  0.04     0.60
## Petal.Length    3 50 1.46 0.17    1.5    1.46 0.15 1.0 1.9   0.9  0.10     0.65
## Petal.Width     4 50 0.25 0.11    0.2    0.24 0.00 0.1 0.6   0.5  1.18     1.26
## Species         5 50 1.00 0.00    1.0    1.00 0.00 1.0 1.0   0.0   NaN      NaN
## size            6 50 1.98 0.14    2.0    2.00 0.00 1.0 2.0   1.0 -6.65    43.12
##                se
## Sepal.Length 0.05
## Sepal.Width  0.05
## Petal.Length 0.02
## Petal.Width  0.01
## Species      0.00
## size         0.02
## ------------------------------------------------------------ 
## group: versicolor
##              vars  n mean   sd median trimmed  mad min max range  skew kurtosis
## Sepal.Length    1 50 5.94 0.52   5.90    5.94 0.52 4.9 7.0   2.1  0.10    -0.69
## Sepal.Width     2 50 2.77 0.31   2.80    2.78 0.30 2.0 3.4   1.4 -0.34    -0.55
## Petal.Length    3 50 4.26 0.47   4.35    4.29 0.52 3.0 5.1   2.1 -0.57    -0.19
## Petal.Width     4 50 1.33 0.20   1.30    1.32 0.22 1.0 1.8   0.8 -0.03    -0.59
## Species         5 50 2.00 0.00   2.00    2.00 0.00 2.0 2.0   0.0   NaN      NaN
## size            6 50 1.42 0.50   1.00    1.40 0.00 1.0 2.0   1.0  0.31    -1.94
##                se
## Sepal.Length 0.07
## Sepal.Width  0.04
## Petal.Length 0.07
## Petal.Width  0.03
## Species      0.00
## size         0.07
## ------------------------------------------------------------ 
## group: virginica
##              vars  n mean   sd median trimmed  mad min max range  skew kurtosis
## Sepal.Length    1 50 6.59 0.64   6.50    6.57 0.59 4.9 7.9   3.0  0.11    -0.20
## Sepal.Width     2 50 2.97 0.32   3.00    2.96 0.30 2.2 3.8   1.6  0.34     0.38
## Petal.Length    3 50 5.55 0.55   5.55    5.51 0.67 4.5 6.9   2.4  0.52    -0.37
## Petal.Width     4 50 2.03 0.27   2.00    2.03 0.30 1.4 2.5   1.1 -0.12    -0.75
## Species         5 50 3.00 0.00   3.00    3.00 0.00 3.0 3.0   0.0   NaN      NaN
## size            6 50 1.06 0.24   1.00    1.00 0.00 1.0 2.0   1.0  3.59    11.15
##                se
## Sepal.Length 0.09
## Sepal.Width  0.05
## Petal.Length 0.08
## Petal.Width  0.04
## Species      0.00
## size         0.03&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;aggregate-function&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;&lt;code&gt;aggregate()&lt;/code&gt; function&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;aggregate()&lt;/code&gt; function allows to split the data into subsets and then to compute summary statistics for each. For instance, if we want to compute the mean for the variables &lt;code&gt;Sepal.Length&lt;/code&gt; and &lt;code&gt;Sepal.Width&lt;/code&gt; by &lt;code&gt;Species&lt;/code&gt; and &lt;code&gt;Size&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;aggregate(cbind(Sepal.Length, Sepal.Width) ~ Species + size,
  data = dat,
  mean
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      Species  size Sepal.Length Sepal.Width
## 1     setosa   big     5.800000    4.000000
## 2 versicolor   big     6.282759    2.868966
## 3  virginica   big     6.663830    2.997872
## 4     setosa small     4.989796    3.416327
## 5 versicolor small     5.457143    2.633333
## 6  virginica small     5.400000    2.600000&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;summaryby-from-doby&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;&lt;code&gt;summaryBy()&lt;/code&gt; from &lt;code&gt;{doBy}&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;An alternative is the &lt;code&gt;summaryBy()&lt;/code&gt; function from the &lt;code&gt;{doBy}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# summary statistics by group
library(doBy)
summaryBy(Sepal.Length + Sepal.Width ~ Species,
  data = dat,
  FUN = summary
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      Species Sepal.Length.Min. Sepal.Length.1st Qu. Sepal.Length.Median
## 1     setosa               4.3                4.800                 5.0
## 2 versicolor               4.9                5.600                 5.9
## 3  virginica               4.9                6.225                 6.5
##   Sepal.Length.Mean Sepal.Length.3rd Qu. Sepal.Length.Max. Sepal.Width.Min.
## 1             5.006                  5.2               5.8              2.3
## 2             5.936                  6.3               7.0              2.0
## 3             6.588                  6.9               7.9              2.2
##   Sepal.Width.1st Qu. Sepal.Width.Median Sepal.Width.Mean Sepal.Width.3rd Qu.
## 1               3.200                3.4            3.428               3.675
## 2               2.525                2.8            2.770               3.000
## 3               2.800                3.0            2.974               3.175
##   Sepal.Width.Max.
## 1              4.4
## 2              3.4
## 3              3.8&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you are interested in some specific descriptive statistics, you can easily specify them via the &lt;code&gt;FUN&lt;/code&gt; argument:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summaryBy(Sepal.Length + Sepal.Width ~ Species,
  data = dat,
  FUN = c(mean, var)
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      Species Sepal.Length.mean Sepal.Width.mean Sepal.Length.var
## 1     setosa             5.006            3.428        0.1242490
## 2 versicolor             5.936            2.770        0.2664327
## 3  virginica             6.588            2.974        0.4043429
##   Sepal.Width.var
## 1      0.14368980
## 2      0.09846939
## 3      0.10400408&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;group_by-and-summarise-from-dplyr&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;&lt;code&gt;group_by()&lt;/code&gt; and &lt;code&gt;summarise()&lt;/code&gt; from &lt;code&gt;{dplyr}&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;Another alternative is with the &lt;code&gt;summarise()&lt;/code&gt; and &lt;code&gt;group_by()&lt;/code&gt; functions from the &lt;code&gt;{dplyr}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(dplyr)

group_by(dat, Species) %&amp;gt;%
  summarise(
    mean = mean(Sepal.Length, na.rm = TRUE),
    sd = sd(Sepal.Length, na.rm = TRUE)
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 3
##   Species     mean    sd
##   &amp;lt;fct&amp;gt;      &amp;lt;dbl&amp;gt; &amp;lt;dbl&amp;gt;
## 1 setosa      5.01 0.352
## 2 versicolor  5.94 0.516
## 3 virginica   6.59 0.636&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to do descriptive statistics in R. If you would like to do the same by hand or understand what these statistics represent, I invite you to read the article “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;Descriptive statistics by hand&lt;/a&gt;”.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;(Note that this article is available for download on my &lt;a href=&#34;https://statsandr.gumroad.com/&#34;&gt;Gumroad page&lt;/a&gt;.)&lt;/em&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;Normality tests such as Shapiro-Wilk or Kolmogorov-Smirnov tests can also be used to test whether the data follow a normal distribution or not. However, in practice, normality tests are often considered as too conservative in the sense that for large sample size, a small deviation from the normality may cause the normality condition to be violated. For this reason, it is often the case that the normality condition is verified based on a combination of visual inspections (with histograms and QQ-plots) and formal test (Shapiro-Wilk test for instance).&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Note that the &lt;code&gt;plain.ascii&lt;/code&gt; and &lt;code&gt;style&lt;/code&gt; arguments are needed for this package. In our examples, these arguments are added in the settings of each chunk so they are not visible.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;Note that it is also possible to compute odds ratio and risk ratio. See the vignette of the package for more information on this matter as these ratios are beyond the scope of this article.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Descriptive statistics by hand</title>
      <link>https://statsandr.com/blog/descriptive-statistics-by-hand/</link>
      <pubDate>Sun, 19 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/descriptive-statistics-by-hand/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#location-versus-dispersion-measures&#34; id=&#34;toc-location-versus-dispersion-measures&#34;&gt;Location versus dispersion measures&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#location&#34; id=&#34;toc-location&#34;&gt;Location&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#minimum-and-maximum&#34; id=&#34;toc-minimum-and-maximum&#34;&gt;Minimum and maximum&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#mean&#34; id=&#34;toc-mean&#34;&gt;Mean&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#median&#34; id=&#34;toc-median&#34;&gt;Median&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#odd-number-of-observations&#34; id=&#34;toc-odd-number-of-observations&#34;&gt;Odd number of observations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#even-number-of-observations&#34; id=&#34;toc-even-number-of-observations&#34;&gt;Even number of observations&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#mean-vs.-median&#34; id=&#34;toc-mean-vs.-median&#34;&gt;Mean vs. median&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#st-and-3rd-quartiles&#34; id=&#34;toc-st-and-3rd-quartiles&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(1^{st}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(3^{rd}\)&lt;/span&gt; quartiles&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#q_0.25-q_0.75-and-q_0.5&#34; id=&#34;toc-q_0.25-q_0.75-and-q_0.5&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(q_{0.25}\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(q_{0.75}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(q_{0.5}\)&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#a-note-on-deciles-and-percentiles&#34; id=&#34;toc-a-note-on-deciles-and-percentiles&#34;&gt;A note on deciles and percentiles&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#mode&#34; id=&#34;toc-mode&#34;&gt;Mode&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#quantitative-variables&#34; id=&#34;toc-quantitative-variables&#34;&gt;Quantitative variables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#qualitative-variables&#34; id=&#34;toc-qualitative-variables&#34;&gt;Qualitative variables&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#dispersion&#34; id=&#34;toc-dispersion&#34;&gt;Dispersion&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#range&#34; id=&#34;toc-range&#34;&gt;Range&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#standard-deviation&#34; id=&#34;toc-standard-deviation&#34;&gt;Standard deviation&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#standard-deviation-for-a-population&#34; id=&#34;toc-standard-deviation-for-a-population&#34;&gt;Standard deviation for a population&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#standard-deviation-for-a-sample&#34; id=&#34;toc-standard-deviation-for-a-sample&#34;&gt;Standard deviation for a sample&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#variance&#34; id=&#34;toc-variance&#34;&gt;Variance&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#variance-for-a-population&#34; id=&#34;toc-variance-for-a-population&#34;&gt;Variance for a population&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#variance-for-a-sample&#34; id=&#34;toc-variance-for-a-sample&#34;&gt;Variance for a sample&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#standard-deviation-vs.-variance&#34; id=&#34;toc-standard-deviation-vs.-variance&#34;&gt;Standard deviation vs. variance&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#notations&#34; id=&#34;toc-notations&#34;&gt;Notations&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#interquartile-range&#34; id=&#34;toc-interquartile-range&#34;&gt;Interquartile range&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#coefficient-of-variation&#34; id=&#34;toc-coefficient-of-variation&#34;&gt;Coefficient of variation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#coefficient-of-variation-vs.-standard-deviation&#34; id=&#34;toc-coefficient-of-variation-vs.-standard-deviation&#34;&gt;Coefficient of variation vs. standard deviation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand_files/descriptive-statistics-by-hand.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;This article explains how to compute the main descriptive statistics by hand and how to interpret them. To learn how to compute these measures in R, read the article “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;Descriptive statistics in R&lt;/a&gt;”.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Descriptive statistics&lt;/strong&gt; (in the broad sense of the term) is a branch of statistics aiming at &lt;strong&gt;summarizing, describing and presenting a series of values or a dataset&lt;/strong&gt;. Long series of values without any preparation or without any summary measures are often not informative due to the difficulty of recognizing any pattern in the data. Below an example with the height (in cm) of a population of 100 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;188.7&lt;/em&gt;, &lt;em&gt;169.4&lt;/em&gt;, &lt;em&gt;178.6&lt;/em&gt;, &lt;em&gt;181.3&lt;/em&gt;, &lt;em&gt;179&lt;/em&gt;, &lt;em&gt;173.9&lt;/em&gt;, &lt;em&gt;190.1&lt;/em&gt;, &lt;em&gt;174.1&lt;/em&gt;, &lt;em&gt;195.2&lt;/em&gt;, &lt;em&gt;174.4&lt;/em&gt;, &lt;em&gt;188&lt;/em&gt;, &lt;em&gt;197.9&lt;/em&gt;, &lt;em&gt;161.1&lt;/em&gt;, &lt;em&gt;172.2&lt;/em&gt;, &lt;em&gt;173.7&lt;/em&gt;, &lt;em&gt;181.4&lt;/em&gt;, &lt;em&gt;172.2&lt;/em&gt;, &lt;em&gt;148.4&lt;/em&gt;, &lt;em&gt;150.6&lt;/em&gt;, &lt;em&gt;188.2&lt;/em&gt;, &lt;em&gt;171.9&lt;/em&gt;, &lt;em&gt;157.2&lt;/em&gt;, &lt;em&gt;173.3&lt;/em&gt;, &lt;em&gt;187.1&lt;/em&gt;, &lt;em&gt;194&lt;/em&gt;, &lt;em&gt;170.7&lt;/em&gt;, &lt;em&gt;172.4&lt;/em&gt;, &lt;em&gt;157.4&lt;/em&gt;, &lt;em&gt;179.6&lt;/em&gt;, &lt;em&gt;168.6&lt;/em&gt;, &lt;em&gt;179.6&lt;/em&gt;, &lt;em&gt;182&lt;/em&gt;, &lt;em&gt;185.4&lt;/em&gt;, &lt;em&gt;168.9&lt;/em&gt;, &lt;em&gt;180&lt;/em&gt;, &lt;em&gt;157.8&lt;/em&gt;, &lt;em&gt;167.2&lt;/em&gt;, &lt;em&gt;166.5&lt;/em&gt;, &lt;em&gt;150.9&lt;/em&gt;, &lt;em&gt;175.4&lt;/em&gt;, &lt;em&gt;177.1&lt;/em&gt;, &lt;em&gt;171.4&lt;/em&gt;, &lt;em&gt;182.6&lt;/em&gt;, &lt;em&gt;167.7&lt;/em&gt;, &lt;em&gt;161.3&lt;/em&gt;, &lt;em&gt;179.3&lt;/em&gt;, &lt;em&gt;166.9&lt;/em&gt;, &lt;em&gt;189.4&lt;/em&gt;, &lt;em&gt;170.7&lt;/em&gt;, &lt;em&gt;181.6&lt;/em&gt;, &lt;em&gt;178.2&lt;/em&gt;, &lt;em&gt;167.2&lt;/em&gt;, &lt;em&gt;190.8&lt;/em&gt;, &lt;em&gt;181.4&lt;/em&gt;, &lt;em&gt;175.9&lt;/em&gt;, &lt;em&gt;177.8&lt;/em&gt;, &lt;em&gt;181.8&lt;/em&gt;, &lt;em&gt;175.9&lt;/em&gt;, &lt;em&gt;145.1&lt;/em&gt;, &lt;em&gt;177.8&lt;/em&gt;, &lt;em&gt;171.3&lt;/em&gt;, &lt;em&gt;176.9&lt;/em&gt;, &lt;em&gt;180.8&lt;/em&gt;, &lt;em&gt;189&lt;/em&gt;, &lt;em&gt;167.7&lt;/em&gt;, &lt;em&gt;188&lt;/em&gt;, &lt;em&gt;178.4&lt;/em&gt;, &lt;em&gt;185.4&lt;/em&gt;, &lt;em&gt;184.2&lt;/em&gt;, &lt;em&gt;182.2&lt;/em&gt;, &lt;em&gt;164.6&lt;/em&gt;, &lt;em&gt;174.1&lt;/em&gt;, &lt;em&gt;181.2&lt;/em&gt;, &lt;em&gt;165.5&lt;/em&gt;, &lt;em&gt;169.6&lt;/em&gt;, &lt;em&gt;180.8&lt;/em&gt;, &lt;em&gt;182.7&lt;/em&gt;, &lt;em&gt;179.6&lt;/em&gt;, &lt;em&gt;166.1&lt;/em&gt;, &lt;em&gt;164&lt;/em&gt;, &lt;em&gt;190.1&lt;/em&gt;, &lt;em&gt;177.6&lt;/em&gt;, &lt;em&gt;175.9&lt;/em&gt;, &lt;em&gt;173.8&lt;/em&gt;, &lt;em&gt;163.1&lt;/em&gt;, &lt;em&gt;181.1&lt;/em&gt;, &lt;em&gt;172.8&lt;/em&gt;, &lt;em&gt;173.2&lt;/em&gt;, &lt;em&gt;184.3&lt;/em&gt;, &lt;em&gt;183.2&lt;/em&gt;, &lt;em&gt;188.9&lt;/em&gt;, &lt;em&gt;170.2&lt;/em&gt;, &lt;em&gt;181.5&lt;/em&gt;, &lt;em&gt;188.9&lt;/em&gt;, &lt;em&gt;163.9&lt;/em&gt;, &lt;em&gt;166.4&lt;/em&gt;, &lt;em&gt;163.7&lt;/em&gt;, &lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Facing this series, it is hard (not to say impossible) for anyone to understand the data and have a clear view of the size of these adults in a reasonable amount of time. Descriptive statistics allow to summarize, and thus have a better overview of the data. Of course, by summarizing data through one or several measures, some information will inevitably be lost. However, in many cases it is generally better to lose some information but in return gain an overview.&lt;/p&gt;
&lt;p&gt;Descriptive statistics is often the first step and an important part in any statistical analysis. It allows to check the quality of the data by detecting potential &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt; (i.e., data points that appear to be separated from the rest of the data), collection or encoding errors. It also helps to “understand” the data and if well presented, descriptive statistics is already a good starting point for further analyses.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;location-versus-dispersion-measures&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Location versus dispersion measures&lt;/h1&gt;
&lt;p&gt;Several different measures (called statistics if we are analyzing a sample) are used to summarize the data. Some of them give an understanding about the &lt;strong&gt;location&lt;/strong&gt; of the data, others give and understanding about the &lt;strong&gt;dispersion&lt;/strong&gt; of the data. In practice, both types of measures are often used together in order to summarize the data in the most concise but complete way.&lt;/p&gt;
&lt;p&gt;We illustrate this point with the graph below, representing the height (in cm) of 100 persons divided into two groups (50 persons in each group):&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand_files/figure-html/unnamed-chunk-2-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The black line corresponds to the mean. The mean height (in cm) is similar in both groups. However, it is clear that the dispersion of heights are very different in the two groups. For this reason, location or dispersion measures are often not enough if presented individually and it is a good practice to present several statistics from both types of measures.&lt;/p&gt;
&lt;p&gt;In the following sections, we detail the most common location and dispersion measures and illustrate them with examples. Note that for the sake of simplicity, we consider only series of values (i.e., univariate data) and not bivariate or multivariate data, and we do not consider the case of series grouped in classes.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;location&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Location&lt;/h1&gt;
&lt;p&gt;Location measures allow to see “where” the data are located, around which values. In other words, location measures give an understanding on &lt;strong&gt;what is the central tendency&lt;/strong&gt;, the “position” of the data as a whole. It includes the following statistics (others exist but we focus on the most common ones):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;minimum&lt;/li&gt;
&lt;li&gt;maximum&lt;/li&gt;
&lt;li&gt;mean&lt;/li&gt;
&lt;li&gt;median&lt;/li&gt;
&lt;li&gt;first quartile&lt;/li&gt;
&lt;li&gt;third quartile&lt;/li&gt;
&lt;li&gt;mode&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We detail and compute by hand each of them in the following sections.&lt;/p&gt;
&lt;div id=&#34;minimum-and-maximum&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Minimum and maximum&lt;/h2&gt;
&lt;p&gt;Minimum (&lt;span class=&#34;math inline&#34;&gt;\(min\)&lt;/span&gt;) and maximum (&lt;span class=&#34;math inline&#34;&gt;\(max\)&lt;/span&gt;) are simply the lowest and largest values, respectively. Given the height (in cm) of a sample of 6 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;188.7&lt;/em&gt;, &lt;em&gt;169.4&lt;/em&gt;, &lt;em&gt;178.6&lt;/em&gt;, &lt;em&gt;181.3&lt;/em&gt;, &lt;em&gt;179&lt;/em&gt; and &lt;em&gt;173.9&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The minimum is 169.4 cm and the maximum is 188.7 cm. These two basic statistics give a clear idea about the size of the smallest and tallest of these 6 adults.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;mean&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Mean&lt;/h2&gt;
&lt;p&gt;The mean, also known as average, is probably the most common statistics. It gives an idea on what is the average value, that is, the central value of the data or in other words the center of gravity:&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;div style=&#34;text-align:center&#34;&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand_files/mean.png&#34; alt=&#34;Mean. Source: LFSAB1105 at UCLouvain&#34; style=&#34;width: 80%;&#34;&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The mean is found by summing all values and dividing the total by the number of observations (denoted &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt;):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[mean = \bar{x} = \frac{\text{sum of all values}}{\text{number of values}} = \frac{1}{n}\sum^{n}_{i = 1} x_i\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Given our sample of 6 adults presented above, the mean is:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\bar{x} = \frac{188.7 + 169.4 + 178.6}{6}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[\frac{+ 181.3 + 179 + 173.9}{6}\\ = 178.4833\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In conclusion, the mean size, that is, the average size of our sample of 6 adults is 178.48 cm (rounded to 2 decimals).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;median&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Median&lt;/h2&gt;
&lt;p&gt;The median is another measure of location so it also gives an idea about the central tendency of the data. The interpretation of the median is that there are as many observations below as above the median. In other words, 50% of the observations lie below the median, and 50% of the observations lie above the median. Below a visual representation of the median:&lt;/p&gt;
&lt;div style=&#34;text-align: center;&#34;&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand_files/median.png&#34; alt=&#34;Median. Source: LFSAB1105 at UCLouvain&#34; style=&#34;width: 80%;&#34;&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The easiest way to compute the median is by first sorting the data from lowest to highest (i.e., in ascending order) then take the middle point as the median. From the sorted values, for an odd number of observations, the middle point is easy to find: it is the value with as many observations below as above. Still from the sorted values, for an even number of observations, the middle point is exactly between the two middle values. Formally, after sorting, the median is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;if &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; (number of observations) is odd: &lt;span class=&#34;math display&#34;&gt;\[med(x) = x_{\frac{n+1}{2}}\]&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;if &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is even: &lt;span class=&#34;math display&#34;&gt;\[med(x) = \frac{1}{2}\big(x_{\frac{n}{2}} + x_{\frac{n}{2} + 1}\big)\]&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;where the subscript of &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt; denotes the numbering of the sorted data. The formulas look harder than they really are, so let’s see with two concrete examples.&lt;/p&gt;
&lt;div id=&#34;odd-number-of-observations&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Odd number of observations&lt;/h3&gt;
&lt;p&gt;Given the height of a sample of 7 adults taken from the 100 adults presented in the introduction:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;188.9&lt;/em&gt;, &lt;em&gt;163.9&lt;/em&gt;, &lt;em&gt;166.4&lt;/em&gt;, &lt;em&gt;163.7&lt;/em&gt;, &lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;We first sort the order from lowest to highest:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;163.7&lt;/em&gt;, &lt;em&gt;163.9&lt;/em&gt;, &lt;em&gt;166.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt;, &lt;em&gt;181.5&lt;/em&gt; and &lt;em&gt;188.9&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Given that the number of observations &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is odd (since &lt;span class=&#34;math inline&#34;&gt;\(n = 7\)&lt;/span&gt;), the median is&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[med(x) = x_\frac{7 + 1}{2} = x_4\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;So we take the fourth value from the sorted values, which corresponds to 166.4. In conclusion, the median size of these 7 adults is 166.4 cm. As you can see, there are 3 observations below 166.4 and 3 observations above 166.4 cm.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;even-number-of-observations&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Even number of observations&lt;/h3&gt;
&lt;p&gt;Now let’s see when the number of observations is even, which is slightly more complicated than when the number of observations is odd. Given the height of a sample of 6 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;188.7&lt;/em&gt;, &lt;em&gt;169.4&lt;/em&gt;, &lt;em&gt;178.6&lt;/em&gt;, &lt;em&gt;181.3&lt;/em&gt;, &lt;em&gt;179&lt;/em&gt; and &lt;em&gt;173.9&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;We sort the values in ascending order:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;169.4&lt;/em&gt;, &lt;em&gt;173.9&lt;/em&gt;, &lt;em&gt;178.6&lt;/em&gt;, &lt;em&gt;179&lt;/em&gt;, &lt;em&gt;181.3&lt;/em&gt; and &lt;em&gt;188.7&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Given that the number of observations &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is even (since &lt;span class=&#34;math inline&#34;&gt;\(n = 6\)&lt;/span&gt;), the median is&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[med(x) = \frac{1}{2}\big(x_{\frac{6}{2}} + x_{\frac{6}{2} + 1}\big) = \frac{1}{2}\big(x_{3} + x_{4}\big)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;So we sum the third and fourth values from the sorted values and divide the total by 2 (which is equivalent than taking the mean of these two middle values):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\frac{1}{2}(178.6 + 179) = 178.8\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In conclusion, the median size of these 6 adults is 178.8 cm. Again, remark that there are as many observations below as above 178.8 cm.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;mean-vs.-median&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Mean vs. median&lt;/h2&gt;
&lt;p&gt;Although the mean and median are often relatively close to each other (in particular when the distribution is symmetric) they should not be confused since they both have advantages and disadvantages in different contexts. Besides the fact that almost everyone knows (or at least have heard about) the mean, it has the advantage that it gives a unique picture for each different series of data. However, it has the disadvantage that the mean is sensible to &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt; (i.e., extreme values). On the other hand, the advantage of the median is that it is resistant to outliers and the inconvenient is that it may be the exact same value for very different series of data (so not unique to the data).&lt;/p&gt;
&lt;p&gt;To illustrate the “sensible to outlier” argument, consider 3 friends in a bar comparing their salaries. Their salaries are &lt;em&gt;1800&lt;/em&gt;, &lt;em&gt;2000&lt;/em&gt; and &lt;em&gt;2100&lt;/em&gt;€, for an average (mean) salary of &lt;em&gt;1967&lt;/em&gt;€. A friend of them (who happens to be friend with Bill Gates as well) joins them in the bar. Their salaries are now &lt;em&gt;1800&lt;/em&gt;, &lt;em&gt;2000&lt;/em&gt;, &lt;em&gt;2100&lt;/em&gt; and &lt;em&gt;1000000&lt;/em&gt;€. The average salary of the 4 friends is now &lt;em&gt;251475&lt;/em&gt;€, compared to &lt;em&gt;1967&lt;/em&gt;€ without the rich friend. Although it is statistically correct to say that the mean salary of the 4 friends is &lt;em&gt;251475&lt;/em&gt;€, you will concede that this measure does not represent a fair image of the salaries of the 4 friends, as 3 of them earn much less than the mean salary. As we have just seen, the mean is sensible to outliers. (&lt;em&gt;Note:&lt;/em&gt; this example also shows how a large majority of citizens earn less than the mean salary reported in the news. For the french-speaking readers, see this &lt;a href=&#34;https://www.youtube.com/watch?v=uIx2xvdwIIo&#34;&gt;video&lt;/a&gt; for more information.)&lt;/p&gt;
&lt;p&gt;On the other hand, if we report the medians, we see that the median salary of the 3 first friends is &lt;em&gt;2000&lt;/em&gt;€, and the median salary of the 4 friends is &lt;em&gt;2050&lt;/em&gt;€. As you can see with this example, the median is not sensible to outliers and for series with such extreme value(s), the median is more appropriate compared to the mean as it often gives a better representation of the data.&lt;/p&gt;
&lt;p&gt;Given the previous example, one may then choose to always use the median instead of the mean. However, the median has it own inconvenient which the mean does not have: the median is less unique and less specific to its underlying data than the mean. Consider the following data, representing the grades of 5 students taking a statistics and economics exam:&lt;/p&gt;
&lt;table style=&#34;width:51%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;16%&#34; /&gt;
&lt;col width=&#34;16%&#34; /&gt;
&lt;col width=&#34;18%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt;studentID&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;economics&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;statistics&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;7&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;3&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;4&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;18&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;5&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;20&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;11&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;br&gt;
The median of the grades is the same in economics and statistics (median = &lt;em&gt;10&lt;/em&gt;). Therefore, had we computed only the medians, we could have concluded that the students performed as well in economics as in statistics. However, although the medians are exactly the same for both classes, it is clear that students performed better in economics than in statistics (compare both grades for each student to see for yourself). In fact, the mean of the grades in economics is &lt;em&gt;13.6&lt;/em&gt; and the mean of the grades in statistics is &lt;em&gt;8.6&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;What we have just shown here is that the median is based only on one single value, the middle value, or on the two middle values if there are an even number of observations, while the mean is based on all values (and thus includes more information). The median is therefore not sensible to outliers, but it is also not unique (i.e., not specific) to different series of data, whereas the mean is much more likely to be different and unique for different series of data. This difference in terms of specificity and uniqueness between the two measures may make the mean more useful for data with no outlier.&lt;/p&gt;
&lt;p&gt;In conclusion, depending on the context and the data, it is often more interesting to report the mean or the median, or both. As a last remark regarding the comparison between the two most important location measures, note that when the mean and median are equal, the distribution of your data can often be considered to follow a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution&lt;/a&gt; (also referred as a Gaussian distribution).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;st-and-3rd-quartiles&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;&lt;span class=&#34;math inline&#34;&gt;\(1^{st}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(3^{rd}\)&lt;/span&gt; quartiles&lt;/h2&gt;
&lt;p&gt;The first and third quartiles are similar to the median in the sense that they also divide the observations into two parts, except that these parts are not equal. Remind that the median divides the data into two equal parts (with 50% of the observations below and 50% above the median).&lt;/p&gt;
&lt;p&gt;The first quartile cuts the observations such that there are 25% of the observations &lt;strong&gt;below&lt;/strong&gt; and thus 75% &lt;strong&gt;above&lt;/strong&gt; the first quartile. The third quartile, as you have guessed by now, represents the value with 75% of the observations below it and thus 25% of the observations above it. There exists several methods to compute the first and third quartile (which sometimes give slight differences, R for instance uses a different method), but here is I believe the easiest one when computing these statistics by hand:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;sort the data in ascending order&lt;/li&gt;
&lt;li&gt;compute &lt;span class=&#34;math inline&#34;&gt;\(0.25 \cdot n\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(0.75 \cdot n\)&lt;/span&gt; (i.e., 0.25 and 0.75 times the number of observations)&lt;/li&gt;
&lt;li&gt;round up these two numbers to the next whole number&lt;/li&gt;
&lt;li&gt;these two numbers represent the rank of the first and third quartile (in the sorted series), respectively&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The steps are the same for both an odd and even number of observations. Here is an example with the following series, representing the height in cm of 9 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;170.2&lt;/em&gt;, &lt;em&gt;181.5&lt;/em&gt;, &lt;em&gt;188.9&lt;/em&gt;, &lt;em&gt;163.9&lt;/em&gt;, &lt;em&gt;166.4&lt;/em&gt;, &lt;em&gt;163.7&lt;/em&gt;, &lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;We first order from lowest to highest:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;163.7&lt;/em&gt;, &lt;em&gt;163.9&lt;/em&gt;, &lt;em&gt;166.4&lt;/em&gt;, &lt;em&gt;170.2&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt;, &lt;em&gt;181.5&lt;/em&gt;, &lt;em&gt;181.5&lt;/em&gt; and &lt;em&gt;188.9&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;There are 9 observations so &lt;span class=&#34;math display&#34;&gt;\[0.25 \cdot 9 = 2.25\]&lt;/span&gt; and &lt;span class=&#34;math display&#34;&gt;\[0.75 \cdot 9 = 6.75\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Rounding up to the whole number gives 3 and 7, which represent the rank of the first and third quartiles, respectively. Therefore, the first quartile is 163.9 cm and the third quartile is 181.5 cm.&lt;/p&gt;
&lt;p&gt;In conclusion, 25% of adults are less than 163.9 cm tall (and thus 75% of them are more than 163.9 cm tall), while 75% of adults are less than 181.5 cm tall (and thus 25% of them are more than 181.5 cm tall).&lt;/p&gt;
&lt;div id=&#34;q_0.25-q_0.75-and-q_0.5&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;&lt;span class=&#34;math inline&#34;&gt;\(q_{0.25}\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(q_{0.75}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(q_{0.5}\)&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Note that the first quartile is denoted &lt;span class=&#34;math inline&#34;&gt;\(q_{0.25}\)&lt;/span&gt; and the third quartile is denoted &lt;span class=&#34;math inline&#34;&gt;\(q_{0.75}\)&lt;/span&gt; (where &lt;span class=&#34;math inline&#34;&gt;\(q\)&lt;/span&gt; stands for quartile). As you can see, the median is actually the second quartile and for this reason it is also sometimes denoted &lt;span class=&#34;math inline&#34;&gt;\(q_{0.5}\)&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;a-note-on-deciles-and-percentiles&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;A note on deciles and percentiles&lt;/h3&gt;
&lt;p&gt;Deciles and percentiles are similar to quartiles except that they cuts the data in 10 and 100 equal parts. For instance, the &lt;span class=&#34;math inline&#34;&gt;\(4^{th}\)&lt;/span&gt; decile (&lt;span class=&#34;math inline&#34;&gt;\(q_{0.4}\)&lt;/span&gt;) is the value such that there are 40% of the observations below it and thus 60% of the observations above it.&lt;/p&gt;
&lt;p&gt;Percentiles follow the same logic. For example, the &lt;span class=&#34;math inline&#34;&gt;\(98^{th}\)&lt;/span&gt; percentile (&lt;span class=&#34;math inline&#34;&gt;\(q_{0.98}\)&lt;/span&gt;, also sometimes denoted &lt;span class=&#34;math inline&#34;&gt;\(P98\)&lt;/span&gt;) is the value such that there are 98% of the observations below it and thus 2% of the observations above it. Percentiles are often used for the weight and height of babies, giving precise information to the parents about where their child stands compared to other children of the same age.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;mode&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Mode&lt;/h2&gt;
&lt;p&gt;The mode of a series is the value that appears most often. In other words, it is the value that has the highest number of occurrences.&lt;/p&gt;
&lt;p&gt;Unlike some descriptive statistics that can only be computed for quantitative variables (the mean for instance), the mode can be computed for quantitative &lt;strong&gt;and&lt;/strong&gt; qualitative variables (see a recap of the different &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/&#34;&gt;types of variables&lt;/a&gt; if you do not remember the difference).&lt;/p&gt;
&lt;div id=&#34;quantitative-variables&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Quantitative variables&lt;/h3&gt;
&lt;p&gt;Given the height of 9 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;170&lt;/em&gt;, &lt;em&gt;168&lt;/em&gt;, &lt;em&gt;171&lt;/em&gt;, &lt;em&gt;170&lt;/em&gt;, &lt;em&gt;182&lt;/em&gt;, &lt;em&gt;165&lt;/em&gt;, &lt;em&gt;170&lt;/em&gt;, &lt;em&gt;189&lt;/em&gt; and &lt;em&gt;167&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The mode is 170 because it is the most common value with 3 occurrences. All other values appear only once.&lt;/p&gt;
&lt;p&gt;Note that it is possible that a series has no mode or more than one mode:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the series &lt;em&gt;4&lt;/em&gt;, &lt;em&gt;7&lt;/em&gt;, &lt;em&gt;2&lt;/em&gt; and &lt;em&gt;10&lt;/em&gt; has no mode,&lt;/li&gt;
&lt;li&gt;the series &lt;em&gt;4&lt;/em&gt;, &lt;em&gt;2&lt;/em&gt;, &lt;em&gt;2&lt;/em&gt;, &lt;em&gt;8&lt;/em&gt;, &lt;em&gt;11&lt;/em&gt; and &lt;em&gt;11&lt;/em&gt; has two modes.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Data with two modes are often called bimodal and data with more than two modes are often called multimodal, as opposed to series with one mode which are referred as unimodal.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;qualitative-variables&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Qualitative variables&lt;/h3&gt;
&lt;p&gt;Given the eye color of the 9 adults presented above:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;brown&lt;/em&gt;, &lt;em&gt;brown&lt;/em&gt;, &lt;em&gt;brown&lt;/em&gt;, &lt;em&gt;brown&lt;/em&gt;, &lt;em&gt;blue&lt;/em&gt;, &lt;em&gt;blue&lt;/em&gt;, &lt;em&gt;blue&lt;/em&gt;, &lt;em&gt;brown&lt;/em&gt; and &lt;em&gt;green&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Brown is the most frequent color, so the mode is brown.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;dispersion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Dispersion&lt;/h1&gt;
&lt;p&gt;All previous descriptive statistics helps to get a sense of the location and position of the data. We now present the most common dispersion measures, which help to get a sense of the &lt;strong&gt;dispersion and the variability&lt;/strong&gt; of the data (to which extent a distribution is squeezed or stretched):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;range&lt;/li&gt;
&lt;li&gt;standard deviation&lt;/li&gt;
&lt;li&gt;variance&lt;/li&gt;
&lt;li&gt;interquartile range&lt;/li&gt;
&lt;li&gt;coefficient of variation&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;As for location measures, we detail and compute by hand each of these statistics one by one.&lt;/p&gt;
&lt;div id=&#34;range&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Range&lt;/h2&gt;
&lt;p&gt;The range is the difference between the maximum and the minimum value:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[range = max - min\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Given the height (in cm) of our sample of 6 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;188.7&lt;/em&gt;, &lt;em&gt;169.4&lt;/em&gt;, &lt;em&gt;178.6&lt;/em&gt;, &lt;em&gt;181.3&lt;/em&gt;, &lt;em&gt;179&lt;/em&gt; and &lt;em&gt;173.9&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The range is 188.7 &lt;span class=&#34;math inline&#34;&gt;\(-\)&lt;/span&gt; 169.4 &lt;span class=&#34;math inline&#34;&gt;\(=\)&lt;/span&gt; 19.3 cm. The advantage of the range is that it is extremely easy to compute it and it gives a precise idea about the “length” of the data. The disadvantage is that it relies on the two most extreme values only, so it is highly sensible to &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;standard-deviation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Standard deviation&lt;/h2&gt;
&lt;p&gt;The standard deviation is the most common dispersion measure in statistics. Like the mean for the location measures, if we have to present one statistics which summarizes the spread of the data, it is usually the standard deviation.&lt;/p&gt;
&lt;p&gt;As its name suggests, the standard deviation tells what is the “normal” deviation of the data. It actually computes the &lt;strong&gt;mean deviation from the global mean&lt;/strong&gt;. The larger the standard deviation, the more scattered the data are. On the contrary, the smaller the standard deviation, the more the data are centered around the mean. Below a visual representation of the standard deviation:&lt;/p&gt;
&lt;div style=&#34;text-align: center;&#34;&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand_files/standard-deviation.png&#34; alt=&#34;Standard deviation. Source: LFSAB1105 at UCLouvain&#34; style=&#34;width: 80%;&#34;&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The standard deviation is a bit more complex than the previous statistics in the sense that there are two formulas depending on whether we face a sample or a population. A population includes all members from a specified group, all possible outcomes or measurements that are of interest. A sample consists of some observations drawn from the population, so a part or a subset of the population. For instance, the population may be “&lt;strong&gt;all&lt;/strong&gt; people living in Belgium” and the sample may be “&lt;strong&gt;some&lt;/strong&gt; people living in Belgium”. Read this article on &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;the difference between population and sample&lt;/a&gt; if you want to learn more.&lt;/p&gt;
&lt;div id=&#34;standard-deviation-for-a-population&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Standard deviation for a population&lt;/h3&gt;
&lt;p&gt;The standard deviation for a population, denoted &lt;span class=&#34;math inline&#34;&gt;\(\sigma\)&lt;/span&gt;, is:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\sigma = \sqrt{\frac{1}{n}\sum^n_{i = 1}(x_i - \mu)^2}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;As you can see from the formula, the standard deviation is actually the mean deviation of the data from the global mean &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt;. Note the square for the difference between the observations (&lt;span class=&#34;math inline&#34;&gt;\(x_i\)&lt;/span&gt;) and the mean (&lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt;) to avoid that negative differences are compensated by positive differences.&lt;/p&gt;
&lt;p&gt;For the sake of easiness, imagine a population of only 3 adults (the steps are the same with a large population, the computation is just longer). Below their heights (in cm):&lt;/p&gt;
&lt;p&gt;&lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The mean is 172.6 (rounded to 1 decimal). The standard deviation is thus:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\sigma = \sqrt{\frac{1}{3} \big[(160.4 - 172.6)^2 \\ + (175.8 - 172.6)^2 \\ + (181.5 - 172.6)^2 \big]}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[\sigma = 8.91\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In conclusion, the standard deviation for the heights of these 3 adults is 8.91 cm. This means that, on average, the height of the adults in this population deviates from the mean by 8.91 cm.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;standard-deviation-for-a-sample&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Standard deviation for a sample&lt;/h3&gt;
&lt;p&gt;The standard deviation for a sample is similar to the standard deviation for a population except that we divide by &lt;span class=&#34;math inline&#34;&gt;\(n -1\)&lt;/span&gt; instead of &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; and it is denoted &lt;span class=&#34;math inline&#34;&gt;\(s\)&lt;/span&gt;:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[s = \sqrt{\frac{1}{n-1}\sum^n_{i = 1}(x_i - \bar{x})^2}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Imagine now that the 3 adults presented in the previous section is a sample instead of a population:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The mean is still 172.6 (rounded to 1 decimal) since the mean is the same whether it is a population or a sample. The standard deviation is now:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[s = \sqrt{\frac{1}{3 - 1} \big[(160.4 - 172.6)^2 \\ + (175.8 - 172.6)^2 \\ + (181.5 - 172.6)^2 \big]}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[s = 10.92\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In conclusion, the standard deviation for the heights of these 3 adults is 10.92 cm. The interpretation is the same than for a population.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;variance&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Variance&lt;/h2&gt;
&lt;p&gt;The variance is simply the square of the standard deviation. Put it another way, the standard deviation is the square root of the variance. We also distinguish between the variance for a population and for a sample in the next sections.&lt;/p&gt;
&lt;div id=&#34;variance-for-a-population&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Variance for a population&lt;/h3&gt;
&lt;p&gt;The variance for a population, denoted &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2\)&lt;/span&gt;, is:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\sigma^2 = \frac{1}{n}\sum^n_{i = 1}(x_i - \mu)^2\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;As you can see, the formula for variance is the same than for standard deviation, except that the square root is removed for the variance. Remember the heights of our population of 3 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The standard deviation was 8.91 cm, so the variance of the height of these adults is &lt;span class=&#34;math inline&#34;&gt;\(8.91^2 = 79.39\)&lt;/span&gt; &lt;span class=&#34;math inline&#34;&gt;\(cm^2\)&lt;/span&gt; (see below why the unit of a variance is &lt;span class=&#34;math inline&#34;&gt;\(unit^2\)&lt;/span&gt;).&lt;/p&gt;
&lt;p&gt;If you did not know the standard deviation of the population and needed to compute the variance of the population by hand, here is how:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\sigma^2 = \frac{1}{3} \big[(160.4 - 172.6)^2 \\ + (175.8 - 172.6)^2 \\ + (181.5 - 172.6)^2 \big] \\ = 79.43\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;(The difference with the above result is due to rounding.)&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;variance-for-a-sample&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Variance for a sample&lt;/h3&gt;
&lt;p&gt;Again, the variance for a sample is similar to the variance for a population except that we divide by &lt;span class=&#34;math inline&#34;&gt;\(n - 1\)&lt;/span&gt; instead of &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; and it is denoted &lt;span class=&#34;math inline&#34;&gt;\(s^2\)&lt;/span&gt;:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[s^2 = \frac{1}{n-1}\sum^n_{i = 1}(x_i - \bar{x})^2\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Imagine again that the 3 adults in the previous section is a sample instead of a population:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The standard deviation for this sample was 10.92 cm, so the variance of the height of these adults is &lt;span class=&#34;math inline&#34;&gt;\(10.92^2 = 119.25\)&lt;/span&gt; &lt;span class=&#34;math inline&#34;&gt;\(cm^2\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;If you did not know the standard deviation of the sample and needed to compute the variance of the sample by hand, here is how:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[s^2 = \frac{1}{3 - 1} \big[(160.4 - 172.6)^2 \\ + (175.8 - 172.6)^2 \\ + (181.5 - 172.6)^2 \big] \\ = 119.15\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;(The difference with the above result is due to rounding.)&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;standard-deviation-vs.-variance&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Standard deviation vs. variance&lt;/h2&gt;
&lt;p&gt;Standard deviation and variance are often used interchangeably and both quantify the spread of a given dataset by measuring how far the observations are from their mean. However, the standard deviation can be more easily interpreted because the unit for the standard deviation is the same than the unit of measurement of the data (while it is the &lt;span class=&#34;math inline&#34;&gt;\(unit^2\)&lt;/span&gt; for the variance).&lt;/p&gt;
&lt;p&gt;Following our example of adult heights in cm, the standard deviation is measured in cm while the variance is measured in &lt;span class=&#34;math inline&#34;&gt;\(cm^2\)&lt;/span&gt;. The fact that the standard deviation keeps the same unit than the initial unit of measurement makes it more interpretable and thus more often used in practice.&lt;/p&gt;
&lt;div id=&#34;notations&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Notations&lt;/h3&gt;
&lt;p&gt;For completeness, below a table showing the different notations for variance and standard deviation in case of population and sample:&lt;/p&gt;
&lt;center&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;Population&lt;/th&gt;
&lt;th align=&#34;right&#34;&gt;Sample&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Standard deviation&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(\sigma\)&lt;/span&gt;&lt;/td&gt;
&lt;td align=&#34;right&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(s\)&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Variance&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(\sigma^2\)&lt;/span&gt;&lt;/td&gt;
&lt;td align=&#34;right&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(s^2\)&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;interquartile-range&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Interquartile range&lt;/h2&gt;
&lt;p&gt;Remember the first &lt;span class=&#34;math inline&#34;&gt;\(q_{0.25}\)&lt;/span&gt; and third quartile &lt;span class=&#34;math inline&#34;&gt;\(q_{0.75}\)&lt;/span&gt; presented earlier (see this &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#st-and-3rd-quartiles&#34;&gt;section&lt;/a&gt;). The interquartile range is another measure of dispersion of the data, using the quartiles. It is the difference between the third and first quartile:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[IQR = q_{0.75} - q_{0.25}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Considering the height of the 9 adults presented in the section about the first and third quartile:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;170.2&lt;/em&gt;, &lt;em&gt;181.5&lt;/em&gt;, &lt;em&gt;188.9&lt;/em&gt;, &lt;em&gt;163.9&lt;/em&gt;, &lt;em&gt;166.4&lt;/em&gt;, &lt;em&gt;163.7&lt;/em&gt;, &lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The first quartile was 163.9 cm and the third quartile was 181.5 cm. The IQR is thus:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[IQR = 181.5 - 163.9 = 17.6\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In conclusion, the interquartile range is 17.6 cm. The interquartile range is actually the range (since it is the difference between a higher and a lower value) of the middle data. The graph below may help to understand better the IQR and the quartiles:&lt;/p&gt;
&lt;div style=&#34;text-align: center;&#34;&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand_files/IQR-quartiles.png&#34; alt=&#34;IQR, first and third quartile. Source: LFSAB1105 at UCLouvain&#34; style=&#34;width: 80%;&#34;&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;coefficient-of-variation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Coefficient of variation&lt;/h2&gt;
&lt;p&gt;The last dispersion measure is the coefficient of variation. The coefficient of variation, denoted &lt;span class=&#34;math inline&#34;&gt;\(CV\)&lt;/span&gt;, is the standard deviation divided by the mean. Formally:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[CV = \frac{s}{\bar{x}}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Consider the height of a sample of 4 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;163.7&lt;/em&gt;, &lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The mean is &lt;span class=&#34;math inline&#34;&gt;\(\bar{x} =\)&lt;/span&gt; 170.35 cm and the standard deviation is &lt;span class=&#34;math inline&#34;&gt;\(s =\)&lt;/span&gt; 9.95 cm. (Find the same values as an exercise!) The coefficient of variation is&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[CV = \frac{9.95 \text{ cm}}{170.35 \text{ cm}} = 0.058 = 5.8\%\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In conclusion, the coefficient of variation is 5.8%. Note that, as a rule of thumb, a coefficient of variation greater than 15% usually means that the data are &lt;strong&gt;heterogeneous&lt;/strong&gt; while a coefficient of variation equal to or less than 15% means that the data are &lt;strong&gt;homogeneous&lt;/strong&gt;. Given that the coefficient of variation equals 5.8% in this case, we can conclude that these 4 adults are homogeneous in terms of height.&lt;/p&gt;
&lt;p&gt;Note that the coefficient of variation for a population follows the same formula, except that notations for the mean and the standard deviation differ:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[CV = \frac{\sigma}{\mu}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The interpretation is also the same as for a sample.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;coefficient-of-variation-vs.-standard-deviation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Coefficient of variation vs. standard deviation&lt;/h2&gt;
&lt;p&gt;Although the coefficient of variation is rather unknown to the public, it is, in fact, worth presenting when making descriptive statistics.&lt;/p&gt;
&lt;p&gt;The standard deviation should always be understood in the context of the mean of the data and is dependent on its unit. The standard deviation has the advantage that it tells by how far on average the data is from the mean in terms of unit in which the data has been measured. Standard deviation is useful when considering variables with same units and approximately same means. However, standard deviation becomes less useful when comparing variables with different units or widely different means. For instance, a variable with a standard deviation of 10 cm cannot be compared to a variable with a standard deviation of 12€ to conclude which one of the two is the most dispersed.&lt;/p&gt;
&lt;p&gt;The coefficient of variation is a ratio of two statistics with the same units. It has thus no unit and is independent of the unit in which the data has been measured. Being unit-free, coefficients of variation computed on datasets or variables with different units or widely different means can be compared to conclude, in fine, which data or variables is more (or less) dispersed. For instance, consider a sample of 10 women with their heights in cm and their salaries in €. We cannot compare the dispersion of their weights with the dispersion of their salaries because it is not measured on the same unit/scale. Now suppose that the coefficients of variation are 0.032 and 0.061 respectively for the height and the salary. Based on that, we can conclude that, relative to their respective average, their salaries vary more than their heights for these women. This is the case because the coefficient of variation is larger for the salary compared to the coefficient variation for the height, and a coefficient of variation has no unit (it is a ratio).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Remember that descriptive statistics are useful to describe and present a series of observations in a concise and informative way. There are two families of descriptive statistics: location and dispersion measures. Location measures give information about the position of the data, whereas dispersion measures give information about the variability of the data.&lt;/p&gt;
&lt;p&gt;We showed how to compute the most common descriptive statistics by hand with concrete examples. We also discussed differences between some measures and when it is more appropriate to use one or the other depending on the context and the data at hand.&lt;/p&gt;
&lt;p&gt;This concludes a relatively long article, thanks for reading! If you would like to learn how to compute these measures in R, read the article “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;Descriptive statistics in R&lt;/a&gt;”. A book I recommend for further reading is “&lt;a href=&#34;https://capitaloneshopping.com/p/statistics/VWP5CXD9KP&#34; target=&#34;_blank&#34;&gt;The Art of Statistics&lt;/a&gt;” by David Spiegelhalter. It is a great book for beginners in statistics and covers a wide range of topics.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;This image and the following ones are taken from the LFSAB1105 course syllabus at UCLouvain.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>What is the difference between population and sample?</title>
      <link>https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/</link>
      <pubDate>Sat, 18 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#sample-vs.-population&#34; id=&#34;toc-sample-vs.-population&#34;&gt;Sample vs. population&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#why-a-sample&#34; id=&#34;toc-why-a-sample&#34;&gt;Why a sample?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#representative-sample&#34; id=&#34;toc-representative-sample&#34;&gt;Representative sample&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#paired-samples&#34; id=&#34;toc-paired-samples&#34;&gt;Paired samples&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample_files/difference-between-population-and-sample.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;People often fail to properly distinguish between population and sample. It is however essential in any statistical analysis, starting from &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics&lt;/a&gt; with different formulas for variance and standard deviation depending on whether we face a sample or a population.&lt;/p&gt;
&lt;p&gt;Moreover, the branch of statistics called &lt;a href=&#34;https://statsandr.com/blog/a-shiny-app-for-inferential-statistics-by-hand/&#34;&gt;inferential statistics&lt;/a&gt; is often defined as the science of drawing conclusions about a population from observations made on a representative sample of that population. It is therefore crucial to properly distinguish between the two concepts. So, what exactly is the difference between population and sample?&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;sample-vs.-population&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Sample vs. population&lt;/h1&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample_files/population-sample.png&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Population versus sample. Source: towardsdatascience.com&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;A &lt;strong&gt;population&lt;/strong&gt; includes &lt;strong&gt;all members&lt;/strong&gt; from a specified group, all possible outcomes or measurements that are of interest. The exact population will depend on the scope of the study. For example, say you would like to know whether there is an association between job performance and the amount of home working hours per week in the specific case of Belgian data scientists. In this case, the population might be Belgian data scientists. However, if the scope of the study is more narrow (e.g., the study focuses on french-speaking Belgian data scientists who live at least 30km away from their workplace), then the population will be more specific and include only workers who meet the criteria. The point is that the population should only include people to whom the results will apply.&lt;/p&gt;
&lt;p&gt;A &lt;strong&gt;sample&lt;/strong&gt; consists of some observations drawn from the population, so a part or a &lt;strong&gt;subset of the population&lt;/strong&gt;. The sample is the group of elements who actually participated in the study.&lt;/p&gt;
&lt;p&gt;Members and elements are defined in the broad sense of the term. It may be human. For instance, the population may be “&lt;strong&gt;all&lt;/strong&gt; people living in Belgium” and the sample may be “&lt;strong&gt;some&lt;/strong&gt; people living in Belgium”. It can be anything else too. Say you are testing the effect of a new fertilizer on crop yield. All the crop fields represent your population, whereas the 10 crop fields you tested correspond to your sample. Since a sample is a subset of a population, a sample is always smaller than the population.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; Note that, a population must not necessarily be large. It might be the case that you study such a narrow population (e.g., first-year male bachelor students from your university who passed the statistics exam in June and for whom their parents have been divorced for more than 5 years), that the size of the population is actually rather small.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;why-a-sample&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Why a sample?&lt;/h1&gt;
&lt;p&gt;As mentioned at the beginning of this article, one of the main concern in statistics is being able to draw conclusions about a population from a representative sample. Why using a sample of the population and not directly the population? In general it is almost always impossible to carry out measurements for the entire study population because:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the population is too large. Example: the population of pregnant women. If we want to take measurements on all pregnant women in the world, it will most likely either take too long or cost too much&lt;/li&gt;
&lt;li&gt;the population is virtual. In this case “virtual” population is understood as a “hypothetical” population: it is unlimited in size. Example: for an experimental study, we focus on men with prostate cancer treated with a new treatment. We do not know how many people will be treated, so the population varies, is infinite and uncountable at the present time, and therefore virtual&lt;/li&gt;
&lt;li&gt;the population is not easily reachable. Example: the population of homeless persons in Belgium&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For these reasons, measurements are made on a subgroup of observations from the population, i.e., on a sample of our population. These measures are then used to draw conclusions about the population of interest. With an appropriate methodology and a sufficiently large sample size, the results obtained on a sample are often almost as accurate as those that would be obtained on the entire population.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;representative-sample&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Representative sample&lt;/h1&gt;
&lt;p&gt;Of course, the sample must be selected to be representative of the population under study. If participants are included in a study on a voluntary basis, there is a serious concern that the resulting sample may not be representative of the population. It may be the case that volunteers are different in terms of the parameter&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt; of interest, leading to a selection bias. Another selection bias can occur when, for instance, a researcher collects citizens’ wage, by the means of internet. It might be the case that people having access to internet have different wages than people who do not have access.&lt;/p&gt;
&lt;p&gt;The gold standard to select a sample representative of the population under study is by selecting a &lt;strong&gt;random&lt;/strong&gt; sample. A random sample is a sample selected at random from the population so that each member of the population has an equal chance of being selected. A random sample is usually an unbiased sample, that is, a sample whose randomness is not in doubt.&lt;/p&gt;
&lt;p&gt;In some situations or domains (e.g., in medicine, psychology, etc.) it is complicated or even impossible to obtain a random sample of the population. In such cases, it will be important to consider how representative the resulting sample will be.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;paired-samples&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Paired samples&lt;/h1&gt;
&lt;p&gt;Last but not least, paired samples are samples in which groups (often pairs) of experimental units are linked together by the same experimental conditions. For example, one may measure the hours of sleep for 20 patients before taking a sleeping pill (forming sample A), and then repeat the measurements on the same individuals after they have taken a sleeping pill (forming sample B). Another example is the grades of 25 students at their statistics and economics exam. Among each student, grades for these two exams are undoubtedly associated (to some extent) to each other.&lt;/p&gt;
&lt;p&gt;Paired samples are usually formed when a variable of interest is measured &lt;strong&gt;at different times on the same experimental unit&lt;/strong&gt;. But, paired samples can also occur even when measurements are made at one specific point in time. For example, if we measure the strength in the right and left arm of 30 athletes. Strength in the right and left arm for the same individual are linked to each other, so sample A (for the right arm) and sample B (for the left arm) are paired samples.&lt;/p&gt;
&lt;p&gt;The two measurements for each individual (hours of sleep before and after the sleeping pill, grades at two different exams, or the strength in the right and left arm) and the two samples are of course related. Statistical tools accounting for a relation between the samples exist and should be preferred in that case.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;To summarize, the sample is the group of individuals who participated in the study and the population is the broader group to whom the results will apply. Measurements on the entire population is often too complex or impossible, so representative samples are used to draw conclusions about the population. Samples based on a random selection are often the most representative samples.&lt;/p&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope the article helped you to understand the difference between population and sample. For the interested reader, see the most common &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics&lt;/a&gt; that can be made on a sample or a population.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;There can be, however, many different samples from the same population. This is beyond the scope of this article, and at the moment we assume there is only one sample from a specified population.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;The tools used to describe a population are called parameters, whereas the tools used to describe a sample are referred as statistics. See the most common &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics&lt;/a&gt; for a sample and a population.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>A Shiny app for inferential statistics by hand</title>
      <link>https://statsandr.com/blog/a-shiny-app-for-inferential-statistics-by-hand/</link>
      <pubDate>Wed, 15 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/a-shiny-app-for-inferential-statistics-by-hand/</guid>
      <description>


&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/a-shiny-app-for-inferential-statistics_files/Screenshot%202020-02-04%20at%2011.36.38.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Statistics is divided into four main branches:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Descriptive statistics&lt;/li&gt;
&lt;li&gt;Inferential statistics&lt;/li&gt;
&lt;li&gt;Predictive analysis&lt;/li&gt;
&lt;li&gt;Exploratory analysis&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Descriptive statistics provide a summary of the data; it helps explaining the data in a concise way without losing too much information. Data can be summarized numerically or graphically. See &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics by hand&lt;/a&gt; or &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;in R&lt;/a&gt; to learn more about this branch of statistics.&lt;/p&gt;
&lt;p&gt;The branch of predictive analysis aims at predicting a dependent variable based on one or several independent variables. Depending on the type of data to be predicted, it often encompasses methods such as &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;linear regression&lt;/a&gt; or classification.&lt;/p&gt;
&lt;p&gt;Exploratory analyses focus on using graphical approaches to delve into the data and identify the relationships that exist between the different variables in the dataset. They are therefore more akin to data visualization.&lt;/p&gt;
&lt;p&gt;Inferential statistics uses a random sample of data taken from a population to make inferences, i.e., to draw conclusions about the population (see the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;difference between population and sample&lt;/a&gt;). In other words, information from the sample is used to make generalizations about the parameter of interest in the population.&lt;/p&gt;
&lt;p&gt;The two major tools in inferential statistics are:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;confidence intervals, and&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Here is a Shiny app which helps you to use these two tools:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-201/&#34; target=&#34;_blank&#34;&gt;Statistics-201&lt;/a&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This Shiny app focuses on confidence intervals and &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt; for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 and 2 means (with unpaired and paired samples)&lt;/li&gt;
&lt;li&gt;1 and 2 proportions&lt;/li&gt;
&lt;li&gt;1 and 2 variances&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&#34;how-to-use-this-app&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How to use this app?&lt;/h1&gt;
&lt;p&gt;Follow these steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Open the app via this &lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-201/&#34; target=&#34;_blank&#34;&gt;link&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Choose the parameter(s) you want to do inference for (i.e., mean(s), proportion(s) or variance(s))&lt;/li&gt;
&lt;li&gt;Write your data in Sample. Observations are separated by a comma and the decimal is a point&lt;/li&gt;
&lt;li&gt;Set the null and alternative hypothesis&lt;/li&gt;
&lt;li&gt;Select the significance level (most of the time &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In the results panel (on the right side or below depending on the size of your screen), you will see:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a recap of your sample together with some appropriate descriptive statistics&lt;/li&gt;
&lt;li&gt;the confidence interval&lt;/li&gt;
&lt;li&gt;the hypothesis test&lt;/li&gt;
&lt;li&gt;the interpretation&lt;/li&gt;
&lt;li&gt;and an illustration of the hypothesis test&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;All formulas, steps and computations to arrive at the final results are also provided.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;code&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Code&lt;/h1&gt;
&lt;p&gt;See the last version on &lt;a href=&#34;https://github.com/AntoineSoetewey/statistics-201&#34; target=&#34;_blank&#34;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note that the link may not work if the app has hit the monthly usage limit. Try again later if that is the case.&lt;/em&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope you will find this app useful to do inferential statistics and in particular confidence interval and hypothesis testing by hand.&lt;/p&gt;
&lt;p&gt;If you need to learn more about the structure of a hypothesis test by hand, see this &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;article&lt;/a&gt;. See also this &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;flowchart&lt;/a&gt; to have an overview of the most common statistical tests.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>A Shiny app for simple linear regression by hand and in R</title>
      <link>https://statsandr.com/blog/a-shiny-app-for-simple-linear-regression-by-hand-and-in-r/</link>
      <pubDate>Wed, 15 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/a-shiny-app-for-simple-linear-regression-by-hand-and-in-r/</guid>
      <description>


&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/a-shiny-app-for-simple-linear-regression_files/Screenshot%202020-02-04%20at%2011.45.09.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Simple linear regression is a statistical method to summarize and study relationships between two variables. When more than two variables are of interest, it is referred as multiple linear regression. See this article on &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;linear regression&lt;/a&gt; for more details.&lt;/p&gt;
&lt;p&gt;In this article, we focus only on a Shiny app which allows to perform simple linear regression by hand and in R:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-202/&#34; target=&#34;_blank&#34;&gt;Statistics-202&lt;/a&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&#34;how-to-use-this-app&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How to use this app?&lt;/h1&gt;
&lt;p&gt;Follow these steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Open the app via this &lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-202/&#34; target=&#34;_blank&#34;&gt;link&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Enter your data in the x and y fields. The x field corresponds to the independent variable, while the y field corresponds to the dependent variable&lt;/li&gt;
&lt;li&gt;If you do not want to display the confidence interval around the regression line, uncheck the checkbox under Plot&lt;/li&gt;
&lt;li&gt;Change the x and y-axis labels for the regression plot if needed&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In the results panel (on the right side or below depending on the size of your screen), you will see:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a recap of your dataset together with some appropriate descriptive statistics&lt;/li&gt;
&lt;li&gt;the estimates &lt;span class=&#34;math inline&#34;&gt;\(\beta_0\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(\beta_1\)&lt;/span&gt; and the regression model computed by hand&lt;/li&gt;
&lt;li&gt;the results of the model computed in R&lt;/li&gt;
&lt;li&gt;the regression plot with some key measures&lt;/li&gt;
&lt;li&gt;the interpretations&lt;/li&gt;
&lt;li&gt;and the assumptions to check the validity of the model&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;All formulas, steps and computations to arrive at the final results are also provided.&lt;/p&gt;
&lt;p&gt;Note that although the assumptions are displayed, it is your responsibility to check them to assess the validity of the linear model.&lt;/p&gt;
&lt;p&gt;Last but not least, you can download a report of the results (in HTML) by clicking on the Download button, and you can choose whether you want to include the R code or not.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;code&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Code&lt;/h1&gt;
&lt;p&gt;See the last version on &lt;a href=&#34;https://github.com/AntoineSoetewey/statistics-202&#34; target=&#34;_blank&#34;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note that the link may not work if the app has hit the monthly usage limit. Try again later if that is the case.&lt;/em&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;For further details about what is linear regression and when it is used, please see:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;this &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;post&lt;/a&gt;, and&lt;/li&gt;
&lt;li&gt;the numerous resources on the topic available in textbooks and online.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope you will find this app useful to do simple linear regression by hand and in R.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>A guide on how to read statistical tables</title>
      <link>https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/</link>
      <pubDate>Mon, 06 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/</guid>
      <description>


&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistics-table_files/Probability-distributions-statsandr.com.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Below a Shiny app to help you read the main statistical tables:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-101/&#34; target=&#34;_blank&#34;&gt;Statistics-101&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This Shiny app helps you to compute probabilities for the main probability distributions.&lt;/p&gt;
&lt;div id=&#34;how-to-use-this-app&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How to use this app?&lt;/h1&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Open the app via this &lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-101/&#34; target=&#34;_blank&#34;&gt;link&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Choose the distribution&lt;/li&gt;
&lt;li&gt;Set the parameter(s) of the distribution (the parameters depend of course on the chosen distribution)&lt;/li&gt;
&lt;li&gt;Select whether you want to find the lower tail, upper tail or an interval&lt;/li&gt;
&lt;li&gt;Choose the value of x&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;On the right panel (or below depending on the size of your screen) you will see:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a recap of the data you just entered&lt;/li&gt;
&lt;li&gt;the numerical solution (i.e., the probability)&lt;/li&gt;
&lt;li&gt;a visualization of the solution&lt;/li&gt;
&lt;li&gt;the probability density function together with the mean, the standard deviation and the variance&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;example&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Example&lt;/h1&gt;
&lt;p&gt;Here is an example with the most common distribution: the &lt;strong&gt;&lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Suppose the following problem: The cost of weekly maintenance and repair of a business has been observed over a long period of time and turns out to be distributed according to a normal distribution with an average of 402€ and a standard deviation of 22€. Having set a budget of 439€ for next week, what is the probability that the cost exceeds this budget?&lt;/p&gt;
&lt;p&gt;To solve this problem, follow these steps in the app:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Choose the normal distribution, as it is said that the costs follow a normal distribution&lt;/li&gt;
&lt;li&gt;Set the mean &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; equal to 402, as it is said that the average cost is 402€&lt;/li&gt;
&lt;li&gt;In the statement, the standard deviation is given (and not the variance) so select “Standard deviation &lt;span class=&#34;math inline&#34;&gt;\(\sigma\)&lt;/span&gt;” and set it equal to 22&lt;/li&gt;
&lt;li&gt;We are asked what is the probability the the cost &lt;strong&gt;exceeds&lt;/strong&gt; the budget. Therefore, we look for the probability &lt;strong&gt;above&lt;/strong&gt; a certain x, so select upper tail &lt;span class=&#34;math inline&#34;&gt;\(P(X &amp;gt; x)\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;We are now asked to find the probability that the cost exceeds 439€, so set x equal to 439&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The solution panel gives a recap of the data:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[X ∼ \mathcal{N}(\mu = 402, \sigma^2 = 484)\]&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(484 = 22^2\)&lt;/span&gt;, and the solution: &lt;span class=&#34;math display&#34;&gt;\[P(X &amp;gt; 439) = P(Z &amp;gt; 1.68) = 0.0463\]&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(Z = \frac{X - \mu}{\sigma} = \frac{439 - 402}{22} = 1.68\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(Z ∼ \mathcal{N}(\mu = 0, \sigma^2 = 1)\)&lt;/span&gt; (known as the standard normal distribution). Thus, the probability that the cost next week exceeds the budget of 439€ is 0.0463, or 4.63%.&lt;/p&gt;
&lt;p&gt;It also shows the normal distribution (with &lt;span class=&#34;math inline&#34;&gt;\(\mu = 402\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2 = 484\)&lt;/span&gt;) with the shaded area corresponding to the probability we are looking for. It then gives some details about the density function, the mean, the standard deviation and the variance.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;code&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Code&lt;/h1&gt;
&lt;p&gt;See the last version on &lt;a href=&#34;https://github.com/AntoineSoetewey/statistics-101&#34; target=&#34;_blank&#34;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note that the link may not work if the app has hit the monthly usage limit. Try again later if that is the case.&lt;/em&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope you will find this app useful to compute probabilities for the main distributions.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Variable types and examples</title>
      <link>https://statsandr.com/blog/variable-types-and-examples/</link>
      <pubDate>Mon, 30 Dec 2019 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/variable-types-and-examples/</guid>
      <description>
&lt;link href=&#34;https://statsandr.com/rmarkdown-libs/htmltools-fill/fill.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/rmarkdown-libs/htmlwidgets/htmlwidgets.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;https://statsandr.com/rmarkdown-libs/viz/viz.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;https://statsandr.com/rmarkdown-libs/DiagrammeR-styles/styles.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/rmarkdown-libs/grViz-binding/grViz.js&#34;&gt;&lt;/script&gt;

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#different-types-of-variables-for-different-types-of-statistical-analysis&#34; id=&#34;toc-different-types-of-variables-for-different-types-of-statistical-analysis&#34;&gt;Different types of variables for different types of statistical analysis&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#big-picture&#34; id=&#34;toc-big-picture&#34;&gt;Big picture&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#quantitative&#34; id=&#34;toc-quantitative&#34;&gt;Quantitative&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#discrete&#34; id=&#34;toc-discrete&#34;&gt;Discrete&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#continuous&#34; id=&#34;toc-continuous&#34;&gt;Continuous&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#qualitative&#34; id=&#34;toc-qualitative&#34;&gt;Qualitative&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#nominal&#34; id=&#34;toc-nominal&#34;&gt;Nominal&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#ordinal&#34; id=&#34;toc-ordinal&#34;&gt;Ordinal&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#variable-transformations&#34; id=&#34;toc-variable-transformations&#34;&gt;Variable transformations&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#from-continuous-to-discrete&#34; id=&#34;toc-from-continuous-to-discrete&#34;&gt;From continuous to discrete&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#from-quantitative-to-qualitative&#34; id=&#34;toc-from-quantitative-to-qualitative&#34;&gt;From quantitative to qualitative&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#additional-notes&#34; id=&#34;toc-additional-notes&#34;&gt;Additional notes&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#misleading-data-encoding&#34; id=&#34;toc-misleading-data-encoding&#34;&gt;Misleading data encoding&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;If you happen to work with datasets frequently, you probably know that each row of your dataset represents a different experimental unit (also called &lt;strong&gt;observation&lt;/strong&gt;) and each column represents a different characteristic (called &lt;strong&gt;variable&lt;/strong&gt;):&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio_files/structure-of-dataset.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Structure of a dataset. Source: R for Data Science by Hadley Wickham &amp;amp; Garrett Grolemund&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Structure of a dataset. Source: R for Data Science by Hadley Wickham &amp;amp; Garrett Grolemund&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;If you do some research on the weight and height of 100 students of your university, for example, you will most likely have a dataset containing 100 rows and 3 columns:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;one for the student’s ID (could be anonymized or not),&lt;/li&gt;
&lt;li&gt;one for the weight,&lt;/li&gt;
&lt;li&gt;and one for the height.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;These three columns represent three characteristics of the 100 students. They are called &lt;strong&gt;variables&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In this article, we are going to focus on variables, and in particular on the different types of variable that exist in statistics. (To learn about the different data types in R, read “&lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/&#34;&gt;Data types in R&lt;/a&gt;”.)&lt;/p&gt;
&lt;div id=&#34;different-types-of-variables-for-different-types-of-statistical-analysis&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Different types of variables for different types of statistical analysis&lt;/h2&gt;
&lt;p&gt;First, one may wonder why we are interested in defining the types of our variables of interest.&lt;/p&gt;
&lt;p&gt;The reason why we often class variables into different types is because not all statistical analyses can be performed on all variable types. For instance, it is impossible to compute the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#mean&#34;&gt;mean&lt;/a&gt; of the variable “hair color” as you cannot sum brown and blond hair.&lt;/p&gt;
&lt;p&gt;On the other hand, finding the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#mode&#34;&gt;mode&lt;/a&gt; of a continuous variable does not really make any sense because most of the time there will not be two exact same values, so there will be no mode. And even in the case there is a mode, there will be very few observations with this value. As an example, try finding the mode of the height of the students in your class. If you are lucky, a couple of students will have the same size. However, most of the time, every student will have a different size (especially if heights have been measured in millimeters) and thus there will be no mode. To see what kind of analysis is possible on each type of variable, see more details in the articles “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;Descriptive statistics by hand&lt;/a&gt;” and “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;Descriptive statistics in R&lt;/a&gt;”.&lt;/p&gt;
&lt;p&gt;Similarly, some &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt; can only be performed on certain type of variables. For example, the Pearson &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;correlation&lt;/a&gt; is usually computed on two quantitative variables, while a &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;Chi-square test of independence&lt;/a&gt; is done with two qualitative variables, and a &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student t-test&lt;/a&gt; or &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;ANOVA&lt;/a&gt; requires a mix of one quantitative and one qualitative variable.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;big-picture&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Big picture&lt;/h1&gt;
&lt;p&gt;In statistics, variables are classified into 4 different types:&lt;/p&gt;
&lt;div class=&#34;grViz html-widget html-fill-item&#34; id=&#34;htmlwidget-1&#34; style=&#34;width:100%;height:480px;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-1&#34;&gt;{&#34;x&#34;:{&#34;diagram&#34;:&#34;digraph {\n\n\n\n\n  \&#34;1\&#34; [label = \&#34;Variable\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fillcolor = \&#34;LightGray\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Variable\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;2\&#34; [label = \&#34;Qualitative\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fillcolor = \&#34;LightGray\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Qualitative\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;3\&#34; [label = \&#34;Nominal\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fillcolor = \&#34;LightGray\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Nominal\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;4\&#34; [label = \&#34;Ordinal\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fillcolor = \&#34;LightGray\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Ordinal\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;5\&#34; [label = \&#34;Quantitative\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fillcolor = \&#34;LightGray\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Quantitative\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;6\&#34; [label = \&#34;Discrete\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fillcolor = \&#34;LightGray\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Discrete\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;7\&#34; [label = \&#34;Continuous\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fillcolor = \&#34;LightGray\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Continuous\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;1\&#34;-&gt;\&#34;2\&#34; \n  \&#34;1\&#34;-&gt;\&#34;5\&#34; \n  \&#34;2\&#34;-&gt;\&#34;3\&#34; \n  \&#34;2\&#34;-&gt;\&#34;4\&#34; \n  \&#34;5\&#34;-&gt;\&#34;6\&#34; \n  \&#34;5\&#34;-&gt;\&#34;7\&#34; \n}&#34;,&#34;config&#34;:{&#34;engine&#34;:&#34;dot&#34;,&#34;options&#34;:null}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;We present each type together with examples in the following sections.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;quantitative&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Quantitative&lt;/h1&gt;
&lt;p&gt;A &lt;strong&gt;quantitative&lt;/strong&gt; variable is a variable that reflects a notion of &lt;strong&gt;magnitude&lt;/strong&gt;, that is, if the values it can take are &lt;strong&gt;numbers&lt;/strong&gt;. A quantitative variable represents thus a measure and is numerical.&lt;/p&gt;
&lt;p&gt;Quantitative variables are divided into two types: &lt;strong&gt;discrete&lt;/strong&gt; and &lt;strong&gt;continuous&lt;/strong&gt;. The difference is explained in the following two sections.&lt;/p&gt;
&lt;div id=&#34;discrete&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Discrete&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Quantitative discrete&lt;/strong&gt; variables are variables for which the values it can take are &lt;strong&gt;countable&lt;/strong&gt; and have a &lt;strong&gt;finite number of possibilities&lt;/strong&gt;. The values are often (but not always) integers. Here are some examples of discrete variables:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Number of children per family&lt;/li&gt;
&lt;li&gt;Number of students in a class&lt;/li&gt;
&lt;li&gt;Number of citizens of a country&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Even if it would take a long time to count the citizens of a large country, it is still technically doable. Moreover, for all examples, the number of possibilities is &lt;strong&gt;finite&lt;/strong&gt;. Whatever the number of children in a family, it will never be 3.58 or 7.912 so the number of possibilities is a finite number and thus countable.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;continuous&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Continuous&lt;/h2&gt;
&lt;p&gt;On the other hand, &lt;strong&gt;quantitative continuous&lt;/strong&gt; variables are variables for which the values are &lt;strong&gt;not countable&lt;/strong&gt; and have an &lt;strong&gt;infinite number of possibilities&lt;/strong&gt;. For example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Age&lt;/li&gt;
&lt;li&gt;Weight&lt;/li&gt;
&lt;li&gt;Height&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For simplicity, we usually referred to years, kilograms (or pounds) and centimeters (or feet and inches) for age, weight and height respectively. However, a 28-year-old man could actually be 28 years, 7 months, 16 days, 3 hours, 4 minutes, 5 seconds, 31 milliseconds, 9 nanoseconds old.&lt;/p&gt;
&lt;p&gt;For all measurements, we usually stop at a standard level of granularity, but nothing (except our measurement tools) prevents us from going deeper, leading to an &lt;strong&gt;infinite number of potential values&lt;/strong&gt;. The fact that the values can take an infinite number of possibilities makes it uncountable.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;qualitative&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Qualitative&lt;/h1&gt;
&lt;p&gt;In opposition to quantitative variables, &lt;strong&gt;qualitative&lt;/strong&gt; variables (also referred as categorical variables or &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#factor&#34;&gt;factors&lt;/a&gt; in R) are variables that are &lt;strong&gt;not numerical&lt;/strong&gt; and which &lt;strong&gt;values fit into categories&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In other words, a &lt;strong&gt;qualitative&lt;/strong&gt; variable is a variable which takes as its values modalities, &lt;strong&gt;categories&lt;/strong&gt; or even levels, in contrast to &lt;strong&gt;quantitative&lt;/strong&gt; variables which measure a &lt;strong&gt;quantity&lt;/strong&gt; on each individual.&lt;/p&gt;
&lt;p&gt;Qualitative variables are divided into two types: &lt;strong&gt;nominal&lt;/strong&gt; and &lt;strong&gt;ordinal&lt;/strong&gt;.&lt;/p&gt;
&lt;div id=&#34;nominal&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Nominal&lt;/h2&gt;
&lt;p&gt;A &lt;strong&gt;qualitative nominal&lt;/strong&gt; variable is a qualitative variable where &lt;strong&gt;no ordering&lt;/strong&gt; is possible or implied in the levels.&lt;/p&gt;
&lt;p&gt;For example, the variable gender is nominal because there is no order in the levels (no matter how many levels you consider for the gender—only two with female/male, or more than two with female/male/ungendered/others, levels are &lt;strong&gt;un&lt;/strong&gt;ordered). Eye color is another example of a nominal variable because there is no order among blue, brown or green eyes.&lt;/p&gt;
&lt;p&gt;A nominal variable can have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;two levels (e.g., do you smoke? Yes/No, or are you pregnant? Yes/No), or&lt;/li&gt;
&lt;li&gt;a large number of levels (what is your college major? Each major is a level in that case).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that a qualitative variable with exactly 2 levels is also referred as a &lt;strong&gt;binary&lt;/strong&gt; or &lt;strong&gt;dichotomous&lt;/strong&gt; variable.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;ordinal&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Ordinal&lt;/h2&gt;
&lt;p&gt;On the other hand, a &lt;strong&gt;qualitative ordinal&lt;/strong&gt; variable is a qualitative variable with an &lt;strong&gt;order implied in the levels&lt;/strong&gt;. For instance, if the severity of road accidents has been measured on a scale such as light, moderate and fatal accidents, this variable is a qualitative ordinal variable because there is a clear order in the levels.&lt;/p&gt;
&lt;p&gt;Another good example is health, which can take values such as poor, reasonable, good, or excellent. Again, there is a clear order in these levels so health is in this case a qualitative ordinal variable.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;variable-transformations&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Variable transformations&lt;/h1&gt;
&lt;p&gt;There are two main variable transformations:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;From a continuous to a discrete variable&lt;/li&gt;
&lt;li&gt;From a quantitative to a qualitative variable&lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&#34;from-continuous-to-discrete&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;From continuous to discrete&lt;/h2&gt;
&lt;p&gt;Let’s say we are interested in babies’ ages. The data collected is the age of the babies, so a quantitative continuous variable. However, we may work with only the number of weeks since birth and thus transforming the age into a discrete variable. The variable age remains a quantitative continuous variable but the variable we are working on (i.e., the number of weeks since birth) can be seen as a quantitative discrete variable.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;from-quantitative-to-qualitative&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;From quantitative to qualitative&lt;/h2&gt;
&lt;p&gt;Let’s say we are interested in the Body Mass Index (BMI). For this, a researcher collects data on height and weight of individuals and computes the BMI. The BMI is a quantitative continuous variable but the researcher may want to turn it into a qualitative variable by categorizing individuals below a certain threshold as underweight, above a certain threshold as overweight and the rest as normal weight. The raw BMI is a quantitative continuous variable but the categorization of the BMI makes the transformed variable a qualitative (ordinal) variable, where the levels are in this case underweight &amp;lt; normal &amp;lt; overweight.&lt;/p&gt;
&lt;p&gt;Same goes for age when age is transformed to a qualitative ordinal variable with levels such as minors, adults and seniors. It is also often the case (especially in surveys) that the variable salary (quantitative continuous) is transformed into a qualitative ordinal variable with different range of salaries (e.g., &amp;lt; 1000€, 1000 - 2000€, &amp;gt; 2000€).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;additional-notes&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Additional notes&lt;/h1&gt;
&lt;div id=&#34;misleading-data-encoding&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Misleading data encoding&lt;/h2&gt;
&lt;p&gt;Last but not least, in datasets it is very often the case that numbers are used for qualitative variables. For instance, a researcher may assign the number “1” to women and the number “2” to men (or “0” to the answer “No” and “1” to the answer “Yes”). Despite the numerical classification, the variable gender is still a qualitative variable and not a discrete variable as it may look. The numerical classification is only used to facilitate data collection and data management. It is indeed easier to write the number “1” or “2” instead of “women” or “men”, and thus less prone to encoding errors.&lt;/p&gt;
&lt;p&gt;The same goes for the identification of each observation. Suppose you collected information on 100 students. You may use their student’s ID to identify them in the dataset (so that you can trace them back). Most of the time, students’ ID (or ID in general) are encoded as numeric values. At first sight, it may thus look like a quantitative variable (because it goes from 1 to 100 for example). However, ID is clearly not a quantitative variable because it actually corresponds to an anonymized version of the student’s first and last name. If you think about it, it would make no sense to compute the mean or median on the IDs, as it does not represent a numerical measurement (but rather just an easier way to identify students than with their names).&lt;/p&gt;
&lt;p&gt;If you face this kind of setup, do not forget to &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/#categorical-variables-and-labels-management&#34;&gt;transform&lt;/a&gt; your variable into the right type before performing any statistical analyses. Usually, a basic &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive analysis&lt;/a&gt; (and knowledge about the variables which have been measured) prior to the main statistical analyses is enough to check that all variable types are correct.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to understand the different types of variable. If you would like to learn more about the different data types in R, read the article “&lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/&#34;&gt;Data types in R&lt;/a&gt;”.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
  </channel>
</rss>