<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Hypothesis test on Stats and R</title>
    <link>https://statsandr.com/tags/hypothesis-test/</link>
    <description>Recent content in Hypothesis test 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/hypothesis-test/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>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>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>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>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>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>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>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>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>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>
    
  </channel>
</rss>