<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Basics on Stats and R</title>
    <link>https://statsandr.com/tags/basics/</link>
    <description>Recent content in Basics on Stats and R</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en</language>
    <lastBuildDate>Mon, 27 Nov 2023 00:00:00 +0000</lastBuildDate>
    
	<atom:link href="https://statsandr.com/tags/basics/index.xml" rel="self" type="application/rss+xml" />
    
    
    <item>
      <title>Introduction to data manipulation in R with {dplyr}</title>
      <link>https://statsandr.com/blog/introduction-to-data-manipulation-in-r-with-dplyr/</link>
      <pubDate>Mon, 27 Nov 2023 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/introduction-to-data-manipulation-in-r-with-dplyr/</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;#dplyr-package&#34; id=&#34;toc-dplyr-package&#34;&gt;{dplyr} package&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#filter-observations&#34; id=&#34;toc-filter-observations&#34;&gt;Filter observations&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#the-pipe-operator&#34; id=&#34;toc-the-pipe-operator&#34;&gt;The pipe operator&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#extract-observations&#34; id=&#34;toc-extract-observations&#34;&gt;Extract observations&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#based-on-their-positions&#34; id=&#34;toc-based-on-their-positions&#34;&gt;Based on their positions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#based-on-their-values&#34; id=&#34;toc-based-on-their-values&#34;&gt;Based on their values&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#sample-observations&#34; id=&#34;toc-sample-observations&#34;&gt;Sample observations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#sort-observations&#34; id=&#34;toc-sort-observations&#34;&gt;Sort observations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#select-variables&#34; id=&#34;toc-select-variables&#34;&gt;Select variables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#rename-variables&#34; id=&#34;toc-rename-variables&#34;&gt;Rename variables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#create-or-modify-variables&#34; id=&#34;toc-create-or-modify-variables&#34;&gt;Create or modify variables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#summarize-observations&#34; id=&#34;toc-summarize-observations&#34;&gt;Summarize observations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#identify-distinct-values&#34; id=&#34;toc-identify-distinct-values&#34;&gt;Identify distinct values&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#connected-operations&#34; id=&#34;toc-connected-operations&#34;&gt;Connected operations&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#group-by&#34; id=&#34;toc-group-by&#34;&gt;Group by&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#number-of-observations&#34; id=&#34;toc-number-of-observations&#34;&gt;Number of observations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#number-of-distinct-values&#34; id=&#34;toc-number-of-distinct-values&#34;&gt;Number of distinct values&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#first-last-or-nth-value&#34; id=&#34;toc-first-last-or-nth-value&#34;&gt;First, last or nth value&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#if-else&#34; id=&#34;toc-if-else&#34;&gt;If else&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#case-when&#34; id=&#34;toc-case-when&#34;&gt;Case when&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-and-other-resources&#34; id=&#34;toc-conclusion-and-other-resources&#34;&gt;Conclusion and other resources&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/introduction-to-data-manipulation-in-r-with-dplyr.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 post, we showed how to &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/&#34;&gt;manipulate data in R&lt;/a&gt;. In particular, we illustrated how to create and manipulate vectors, factors, lists and data frames. This served as an introduction to R and was aimed at beginners. Moreover, as long as it was possible, all manipulations were made in base R, that is, without having to load any package.&lt;/p&gt;
&lt;p&gt;In this post, we would like to show again how to manipulate data in R, but this time using the &lt;code&gt;{dplyr}&lt;/code&gt; package.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;{dplyr}&lt;/code&gt; package, developed by Hadley Wickham and colleagues at Posit, provides a complete set of functions that help you solve the most common data manipulation challenges such as:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;filtering observations based on their values&lt;/li&gt;
&lt;li&gt;extracting observations based on their values or positions&lt;/li&gt;
&lt;li&gt;sampling observations based on a specific number or fraction of rows&lt;/li&gt;
&lt;li&gt;sorting observations based on one or several variables&lt;/li&gt;
&lt;li&gt;selecting variables based on their names or positions&lt;/li&gt;
&lt;li&gt;renaming variables&lt;/li&gt;
&lt;li&gt;adding new variables based on existing ones&lt;/li&gt;
&lt;li&gt;summarizing observations or variables to a single descriptive measure&lt;/li&gt;
&lt;li&gt;performing any operation by group&lt;/li&gt;
&lt;li&gt;categorizing observations into two or more groups&lt;/li&gt;
&lt;li&gt;etc.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;More information about the package can be found at &lt;a href=&#34;https://dplyr.tidyverse.org/&#34; target=&#34;_blank&#34;&gt;dplyr.tidyverse.org&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;In this post, we will present the most common functions for data manipulation and data management using the &lt;code&gt;{dplyr}&lt;/code&gt; package (illustrated on a data frame). This is however not an exhaustive list! It is likely that you will need other functions that the ones presented here. For the interested readers, see the end of this post for further resources.&lt;/p&gt;
&lt;p&gt;A question I am often asked is whether it is best to first learn data manipulation with base R and &lt;em&gt;then&lt;/em&gt; with &lt;code&gt;{dplyr}&lt;/code&gt;, or directly learn &lt;code&gt;{dplyr}&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Everyone may not agree, but here is what I tend to answer. The interest in terms of efficiency and clarity/readability of the code that &lt;code&gt;{dplyr}&lt;/code&gt; brings is obvious. So even when I give a &lt;a href=&#34;https://datanalyze.be/trainings/&#34;&gt;training&lt;/a&gt; targeted to statisticians, I present the &lt;code&gt;{dplyr}&lt;/code&gt; package. However, I still do believe that learning data manipulation with base R is important for two reasons:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Everyone will, at some point, be confronted with code written in base R (either from collaboration with other R users, or from code found in textbooks or online).&lt;/li&gt;
&lt;li&gt;Through the feedback I receive from my students, I notice that &lt;code&gt;{dplyr}&lt;/code&gt; is relatively easy to learn when you are familiar with base R (which is quite rewarding for those who struggled at the beginning).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;For these reasons, I tend to teach data manipulation with base R first and then slowly switch to &lt;code&gt;{dplyr}&lt;/code&gt; (up to the point that for some advanced training courses, I hardly use base R at all by the end of the course). As a side note, this is the approach I follow for data visualization in R as well: I teach first how to plot data with base R, then I gradually teach them &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;how to use &lt;code&gt;{ggplot2}&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;With this approach, some students may have the impression that they wasted their time learning base R. At least, some may have this impression during the training. However, as soon as the training is done and they have to learn R by themselves or work on real projects, they are grateful of having learned both.&lt;/p&gt;
&lt;p&gt;I am curious to hear from other teachers regarding their approach, so feel free to share your opinion.&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 present the different functions, we will use the data frame &lt;code&gt;penguins&lt;/code&gt;, available within the &lt;code&gt;{palmerpenguins}&lt;/code&gt; package &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-palmerpenguins2020horst&#34;&gt;Horst et al. 2020&lt;/a&gt;)&lt;/span&gt;. Data are available by &lt;a href=&#34;https://creativecommons.org/public-domain/cc0/&#34; target=&#34;_blank&#34;&gt;CC-0&lt;/a&gt; license and can be downloaded from CRAN:&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;Before going further, we rename the data frame as &lt;code&gt;dat&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- penguins&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I like to call data frames I am working on with a generic name such as &lt;code&gt;dat&lt;/code&gt; for two reasons:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Every time I need to write the name of the data frame, it is usually shorter to write &lt;code&gt;dat&lt;/code&gt; than to write the name of the data frame (which is in this case &lt;code&gt;penguins&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;If I need to do similar analyses or plots on different data frames, the code I wrote in the past can be reused with only a few modifications. With this very simple trick, most of the time I only have to edit the names of the variables, but the name of the data frame does not need to be changed (which saves me a lot of time).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The data frame contains data for 344 penguins and 8 variables describing the species, the island, some measurements of the size of the bill, flipper and body mass, the sex and the study year. More information about the data frame can be found by running &lt;code&gt;?penguins&lt;/code&gt; (after loading the &lt;code&gt;{palmerpenguins}&lt;/code&gt; package).&lt;/p&gt;
&lt;p&gt;For this post, we will focus only on the variables &lt;code&gt;species&lt;/code&gt;, &lt;code&gt;body_mass_g&lt;/code&gt;, &lt;code&gt;sex&lt;/code&gt; and &lt;code&gt;year&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Before proceeding with the different data manipulation techniques, let’s first inspect the data by displaying its structure, the first 6 rows and a summary of it:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;str(dat) # structure of the data&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## tibble [344 × 4] (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 ...
##  $ 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;pre class=&#34;r&#34;&gt;&lt;code&gt;head(dat) # display first 6 rows&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 6 × 4
##   species body_mass_g sex     year
##   &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
## 1 Adelie         3750 male    2007
## 2 Adelie         3800 female  2007
## 3 Adelie         3250 female  2007
## 4 Adelie           NA &amp;lt;NA&amp;gt;    2007
## 5 Adelie         3450 female  2007
## 6 Adelie         3650 male    2007&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(dat) # summary&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       species     body_mass_g       sex           year     
##  Adelie   :152   Min.   :2700   female:165   Min.   :2007  
##  Chinstrap: 68   1st Qu.:3550   male  :168   1st Qu.:2007  
##  Gentoo   :124   Median :4050   NA&amp;#39;s  : 11   Median :2008  
##                  Mean   :4202                Mean   :2008  
##                  3rd Qu.:4750                3rd Qu.:2009  
##                  Max.   :6300                Max.   :2009  
##                  NA&amp;#39;s   :2&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;dplyr-package&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;{dplyr} package&lt;/h1&gt;
&lt;p&gt;Without further ado, let’s illustrate the different functions for data manipulation available in the &lt;code&gt;{dplyr}&lt;/code&gt; package in the following sections.&lt;/p&gt;
&lt;p&gt;As for any package, we first need to install and load it before using it:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# install.packages(&amp;quot;dplyr&amp;quot;)
library(dplyr)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that all functions presented below requires tidy data, which means that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;each variable is in its own column,&lt;/li&gt;
&lt;li&gt;each observation, or case, is in its own row, and&lt;/li&gt;
&lt;li&gt;each value is in its own cell.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;images/tidy-data.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Rules of a tidy data frame: variables are columns, observations are rows, and values are cells. Source: R for Data Science (2e) by H. Wickham, M. Çetinkaya-Rundel and G. Grolemund.&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Rules of a tidy data frame: variables are columns, observations are rows, and values are cells. Source: R for Data Science (2e) by H. Wickham, M. Çetinkaya-Rundel and G. Grolemund.&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;div id=&#34;filter-observations&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Filter observations&lt;/h2&gt;
&lt;p&gt;Filtering observations based on their values can be done with the &lt;code&gt;filter()&lt;/code&gt; function. This function works on both &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#quantitative&#34;&gt;quantitative&lt;/a&gt; and &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;qualitative&lt;/a&gt; variables:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# filter observations based on a quantitative variable
filter(dat, body_mass_g &amp;gt; 4000)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 172 × 4
##    species body_mass_g sex    year
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt; &amp;lt;int&amp;gt;
##  1 Adelie         4675 male   2007
##  2 Adelie         4250 &amp;lt;NA&amp;gt;   2007
##  3 Adelie         4400 male   2007
##  4 Adelie         4500 male   2007
##  5 Adelie         4200 male   2007
##  6 Adelie         4150 male   2007
##  7 Adelie         4650 male   2007
##  8 Adelie         4400 male   2007
##  9 Adelie         4600 male   2007
## 10 Adelie         4150 male   2007
## # ℹ 162 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# filter observations based on a qualitative variable
filter(dat, sex == &amp;quot;female&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 165 × 4
##    species body_mass_g sex     year
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
##  1 Adelie         3800 female  2007
##  2 Adelie         3250 female  2007
##  3 Adelie         3450 female  2007
##  4 Adelie         3625 female  2007
##  5 Adelie         3200 female  2007
##  6 Adelie         3700 female  2007
##  7 Adelie         3450 female  2007
##  8 Adelie         3325 female  2007
##  9 Adelie         3400 female  2007
## 10 Adelie         3800 female  2007
## # ℹ 155 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can combine several conditions with &lt;code&gt;&amp;amp;&lt;/code&gt; (if the conditions must be cumulative) or &lt;code&gt;|&lt;/code&gt; (if the conditions are alternatives), for instance:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# filter observations based on 2 cumulative conditions
filter(dat, body_mass_g &amp;gt; 4000 &amp;amp; sex == &amp;quot;female&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 58 × 4
##    species body_mass_g sex     year
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
##  1 Gentoo         4500 female  2007
##  2 Gentoo         4450 female  2007
##  3 Gentoo         4550 female  2007
##  4 Gentoo         4800 female  2007
##  5 Gentoo         4400 female  2007
##  6 Gentoo         4650 female  2007
##  7 Gentoo         4650 female  2007
##  8 Gentoo         4200 female  2007
##  9 Gentoo         4150 female  2007
## 10 Gentoo         4800 female  2007
## # ℹ 48 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice that variable names do &lt;em&gt;not&lt;/em&gt; have to be written inside single nor double quotation marks (&lt;code&gt;&#39;&#39;&lt;/code&gt; or &lt;code&gt;&#34;&#34;&lt;/code&gt;). This is the case for all functions presented below.&lt;/p&gt;
&lt;div id=&#34;the-pipe-operator&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;The pipe operator&lt;/h3&gt;
&lt;p&gt;As you can see from the code above, the &lt;code&gt;filter()&lt;/code&gt; functions requires the name of the data frame as first argument, then the condition (with the usual logical operators &lt;code&gt;&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;&lt;/code&gt;, &lt;code&gt;&amp;gt;=&lt;/code&gt;, &lt;code&gt;&amp;lt;=&lt;/code&gt;, &lt;code&gt;==&lt;/code&gt;, &lt;code&gt;!=&lt;/code&gt;, &lt;code&gt;%in%&lt;/code&gt;, etc.) as second argument.&lt;/p&gt;
&lt;p&gt;Specifying the name of the data frame as first argument is required for all functions presented in this list. However, there is a workaround to specifying the data frame’s name inside the functions: the pipe operator (&lt;code&gt;|&amp;gt;&lt;/code&gt; or &lt;code&gt;%&amp;gt;%&lt;/code&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;The pipe operator allows to perform a sequence of several operations, that is, chain a sequence of calculations together. It is particularly useful when you are performing several operations on a data frame, and you do not want to save the output at each intermediate step. We will see below how to use the pipe operator with several operations, but for now I would like to introduce it with only one operation at a time.&lt;/p&gt;
&lt;p&gt;As you can see with the &lt;code&gt;filter()&lt;/code&gt; function, the pipe operator is not compulsory. However, I recommend it so much (even to beginners) for its easy of use, convenience, code readability and popularity that from now on functions available in &lt;code&gt;{dplyr}&lt;/code&gt; will be presented together with the pipe operator.&lt;/p&gt;
&lt;p&gt;So with the pipe operator, the code above becomes:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# filter observations based on a quantitative variable
dat |&amp;gt;
  filter(body_mass_g &amp;gt; 4000)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 172 × 4
##    species body_mass_g sex    year
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt; &amp;lt;int&amp;gt;
##  1 Adelie         4675 male   2007
##  2 Adelie         4250 &amp;lt;NA&amp;gt;   2007
##  3 Adelie         4400 male   2007
##  4 Adelie         4500 male   2007
##  5 Adelie         4200 male   2007
##  6 Adelie         4150 male   2007
##  7 Adelie         4650 male   2007
##  8 Adelie         4400 male   2007
##  9 Adelie         4600 male   2007
## 10 Adelie         4150 male   2007
## # ℹ 162 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# filter observations based on a qualitative variable
dat |&amp;gt;
  filter(sex == &amp;quot;female&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 165 × 4
##    species body_mass_g sex     year
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
##  1 Adelie         3800 female  2007
##  2 Adelie         3250 female  2007
##  3 Adelie         3450 female  2007
##  4 Adelie         3625 female  2007
##  5 Adelie         3200 female  2007
##  6 Adelie         3700 female  2007
##  7 Adelie         3450 female  2007
##  8 Adelie         3325 female  2007
##  9 Adelie         3400 female  2007
## 10 Adelie         3800 female  2007
## # ℹ 155 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# filter observations based on 2 cumulative conditions
dat |&amp;gt;
  filter(body_mass_g &amp;gt; 4000 &amp;amp; sex == &amp;quot;female&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 58 × 4
##    species body_mass_g sex     year
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
##  1 Gentoo         4500 female  2007
##  2 Gentoo         4450 female  2007
##  3 Gentoo         4550 female  2007
##  4 Gentoo         4800 female  2007
##  5 Gentoo         4400 female  2007
##  6 Gentoo         4650 female  2007
##  7 Gentoo         4650 female  2007
##  8 Gentoo         4200 female  2007
##  9 Gentoo         4150 female  2007
## 10 Gentoo         4800 female  2007
## # ℹ 48 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The pipe operator simply takes the results of one operation into the next operation below it, making the code extremely easy to write and read.&lt;/p&gt;
&lt;p&gt;This way, instead of specifying the data frame’s name as first argument in the &lt;code&gt;filter()&lt;/code&gt; function (or any other function within the &lt;code&gt;{dplyr}&lt;/code&gt; package), we simply specify the data frame’s name and then the desired function, combined together thanks to the pipe operator.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;extract-observations&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Extract observations&lt;/h2&gt;
&lt;p&gt;It is possible to extract observations based on:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;their positions, or&lt;/li&gt;
&lt;li&gt;their values.&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&#34;based-on-their-positions&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Based on their positions&lt;/h3&gt;
&lt;p&gt;Extracting observations based on their positions can be done with the &lt;code&gt;slice()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# extract rows 2, 5 and 37
dat |&amp;gt;
  slice(c(2, 5, 37))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 4
##   species body_mass_g sex     year
##   &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
## 1 Adelie         3800 female  2007
## 2 Adelie         3450 female  2007
## 3 Adelie         3950 male    2007&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Moreover, extracting the first or last rows can be done with &lt;code&gt;slice_head()&lt;/code&gt; and &lt;code&gt;slice_tail()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# extract first 3 rows
dat |&amp;gt;
  slice_head(n = 3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 4
##   species body_mass_g sex     year
##   &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
## 1 Adelie         3750 male    2007
## 2 Adelie         3800 female  2007
## 3 Adelie         3250 female  2007&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# extract last 3 rows
dat |&amp;gt;
  slice_tail(n = 3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 4
##   species   body_mass_g sex     year
##   &amp;lt;fct&amp;gt;           &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
## 1 Chinstrap        3775 male    2009
## 2 Chinstrap        4100 male    2009
## 3 Chinstrap        3775 female  2009&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;based-on-their-values&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Based on their values&lt;/h3&gt;
&lt;p&gt;To extract observations based on values of a variable, use:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;slice_min()&lt;/code&gt; to select rows with the &lt;strong&gt;lowest&lt;/strong&gt; values (with a defined proportion), and&lt;/li&gt;
&lt;li&gt;&lt;code&gt;slice_max()&lt;/code&gt; to select rows with the &lt;strong&gt;highest&lt;/strong&gt; values (with a defined proportion).&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# extract observations with 25% lowest body mass
dat |&amp;gt;
  slice_min(body_mass_g, prop = 0.25)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 89 × 4
##    species   body_mass_g sex     year
##    &amp;lt;fct&amp;gt;           &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
##  1 Chinstrap        2700 female  2008
##  2 Adelie           2850 female  2008
##  3 Adelie           2850 female  2008
##  4 Adelie           2900 female  2008
##  5 Adelie           2900 female  2008
##  6 Adelie           2900 female  2009
##  7 Chinstrap        2900 female  2007
##  8 Adelie           2925 female  2009
##  9 Adelie           2975 &amp;lt;NA&amp;gt;    2007
## 10 Adelie           3000 female  2007
## # ℹ 79 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# extract observations with 25% highest body mass
dat |&amp;gt;
  slice_max(body_mass_g, prop = 0.25)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 90 × 4
##    species body_mass_g sex    year
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt; &amp;lt;int&amp;gt;
##  1 Gentoo         6300 male   2007
##  2 Gentoo         6050 male   2007
##  3 Gentoo         6000 male   2008
##  4 Gentoo         6000 male   2009
##  5 Gentoo         5950 male   2008
##  6 Gentoo         5950 male   2009
##  7 Gentoo         5850 male   2007
##  8 Gentoo         5850 male   2007
##  9 Gentoo         5850 male   2009
## 10 Gentoo         5800 male   2008
## # ℹ 80 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;sample-observations&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Sample observations&lt;/h2&gt;
&lt;p&gt;Sampling observations can be done in two ways:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Random sample of a &lt;strong&gt;number&lt;/strong&gt; of rows with &lt;code&gt;sample_n()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Random sample of a &lt;strong&gt;fraction&lt;/strong&gt; of rows with &lt;code&gt;sample_frac()&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# random sample of 3 rows
dat |&amp;gt;
  sample_n(size = 3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 4
##   species   body_mass_g sex     year
##   &amp;lt;fct&amp;gt;           &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
## 1 Adelie           3450 female  2007
## 2 Chinstrap        3675 female  2009
## 3 Gentoo           4500 female  2007&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# random sample of half of the rows
dat |&amp;gt;
  sample_frac(size = 1 / 2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 172 × 4
##    species   body_mass_g sex     year
##    &amp;lt;fct&amp;gt;           &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
##  1 Adelie           4150 male    2008
##  2 Gentoo           5800 male    2008
##  3 Adelie           3650 male    2009
##  4 Adelie           3500 male    2009
##  5 Adelie           3450 female  2007
##  6 Adelie           4300 male    2009
##  7 Chinstrap        3400 female  2008
##  8 Adelie           3950 male    2007
##  9 Chinstrap        3325 female  2009
## 10 Adelie           3950 male    2008
## # ℹ 162 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that, as with the &lt;code&gt;sample()&lt;/code&gt; function within base R, &lt;code&gt;size&lt;/code&gt; can be greater than the size of the data frame. In this case, some rows will be duplicated, and you will need to specify the argument &lt;code&gt;replace = TRUE&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Alternatively, it is possible to obtain a random sample of a number of rows or fraction or rows with &lt;code&gt;slice_sample()&lt;/code&gt;. For this, use:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the argument &lt;code&gt;n&lt;/code&gt; to select a number of rows, or&lt;/li&gt;
&lt;li&gt;the argument &lt;code&gt;prop&lt;/code&gt; to select a fraction of rows.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# random sample of 3 rows
dat |&amp;gt;
  slice_sample(n = 3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 4
##   species body_mass_g sex     year
##   &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
## 1 Adelie         3200 female  2007
## 2 Adelie         3800 female  2007
## 3 Gentoo         4800 female  2007&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# random sample of half of the rows
dat |&amp;gt;
  slice_sample(prop = 1 / 2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 172 × 4
##    species body_mass_g sex     year
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
##  1 Adelie         3900 male    2009
##  2 Adelie         3275 female  2009
##  3 Gentoo         5050 male    2008
##  4 Gentoo         4700 female  2009
##  5 Gentoo         4600 female  2008
##  6 Gentoo         4875 &amp;lt;NA&amp;gt;    2009
##  7 Adelie         3700 &amp;lt;NA&amp;gt;    2007
##  8 Gentoo         3950 female  2008
##  9 Gentoo         4550 female  2007
## 10 Adelie         3500 female  2008
## # ℹ 162 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;sort-observations&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Sort observations&lt;/h2&gt;
&lt;p&gt;Sorting observations can be done with the &lt;code&gt;arrange()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# sort observations based on body mass (ascending order)
dat |&amp;gt;
  arrange(body_mass_g)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 4
##    species   body_mass_g sex     year
##    &amp;lt;fct&amp;gt;           &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
##  1 Chinstrap        2700 female  2008
##  2 Adelie           2850 female  2008
##  3 Adelie           2850 female  2008
##  4 Adelie           2900 female  2008
##  5 Adelie           2900 female  2008
##  6 Adelie           2900 female  2009
##  7 Chinstrap        2900 female  2007
##  8 Adelie           2925 female  2009
##  9 Adelie           2975 &amp;lt;NA&amp;gt;    2007
## 10 Adelie           3000 female  2007
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By default, &lt;code&gt;arrange()&lt;/code&gt; uses the &lt;strong&gt;ascending&lt;/strong&gt; order. To sort in &lt;strong&gt;descending&lt;/strong&gt; order, use &lt;code&gt;desc()&lt;/code&gt; inside &lt;code&gt;arrange()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# sort observations based on body mass (descending order)
dat |&amp;gt;
  arrange(desc(body_mass_g))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 4
##    species body_mass_g sex    year
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt; &amp;lt;int&amp;gt;
##  1 Gentoo         6300 male   2007
##  2 Gentoo         6050 male   2007
##  3 Gentoo         6000 male   2008
##  4 Gentoo         6000 male   2009
##  5 Gentoo         5950 male   2008
##  6 Gentoo         5950 male   2009
##  7 Gentoo         5850 male   2007
##  8 Gentoo         5850 male   2007
##  9 Gentoo         5850 male   2009
## 10 Gentoo         5800 male   2008
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As with &lt;code&gt;filter()&lt;/code&gt;, &lt;code&gt;arrange()&lt;/code&gt; can be used for several variables and works both on quantitative and qualitative variables:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# sort observations based on two variables
dat |&amp;gt;
  arrange(sex, body_mass_g)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 4
##    species   body_mass_g sex     year
##    &amp;lt;fct&amp;gt;           &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;
##  1 Chinstrap        2700 female  2008
##  2 Adelie           2850 female  2008
##  3 Adelie           2850 female  2008
##  4 Adelie           2900 female  2008
##  5 Adelie           2900 female  2008
##  6 Adelie           2900 female  2009
##  7 Chinstrap        2900 female  2007
##  8 Adelie           2925 female  2009
##  9 Adelie           3000 female  2007
## 10 Adelie           3000 female  2009
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The code above sorts the observations first based on the sex (in alphabetical order) and then based on the body mass (in ascending order, so from lowest to highest).&lt;/p&gt;
&lt;p&gt;Note that if the qualitative variable is defined as an ordered &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#factor&#34;&gt;factor&lt;/a&gt;, the sorting is based on level order, not alphabetical order!&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;select-variables&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Select variables&lt;/h2&gt;
&lt;p&gt;Selecting variables can be done with the &lt;code&gt;select()&lt;/code&gt; function, based on:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the position of the variable(s), or&lt;/li&gt;
&lt;li&gt;the name(s) of the variable(s).&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# select variables by their positions
dat |&amp;gt;
  select(c(2, 4))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 2
##    body_mass_g  year
##          &amp;lt;int&amp;gt; &amp;lt;int&amp;gt;
##  1        3750  2007
##  2        3800  2007
##  3        3250  2007
##  4          NA  2007
##  5        3450  2007
##  6        3650  2007
##  7        3625  2007
##  8        4675  2007
##  9        3475  2007
## 10        4250  2007
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# select variables by their names
dat |&amp;gt;
  select(body_mass_g, year)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 2
##    body_mass_g  year
##          &amp;lt;int&amp;gt; &amp;lt;int&amp;gt;
##  1        3750  2007
##  2        3800  2007
##  3        3250  2007
##  4          NA  2007
##  5        3450  2007
##  6        3650  2007
##  7        3625  2007
##  8        4675  2007
##  9        3475  2007
## 10        4250  2007
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that it is also possible to remove variables. For this, use the &lt;code&gt;-&lt;/code&gt; sign in front of their positions or names:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# remove variables by their positions
dat |&amp;gt;
  select(-c(2, 4))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 2
##    species sex   
##    &amp;lt;fct&amp;gt;   &amp;lt;fct&amp;gt; 
##  1 Adelie  male  
##  2 Adelie  female
##  3 Adelie  female
##  4 Adelie  &amp;lt;NA&amp;gt;  
##  5 Adelie  female
##  6 Adelie  male  
##  7 Adelie  female
##  8 Adelie  male  
##  9 Adelie  &amp;lt;NA&amp;gt;  
## 10 Adelie  &amp;lt;NA&amp;gt;  
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# remove variables by their names
dat |&amp;gt;
  select(-c(body_mass_g, year))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 2
##    species sex   
##    &amp;lt;fct&amp;gt;   &amp;lt;fct&amp;gt; 
##  1 Adelie  male  
##  2 Adelie  female
##  3 Adelie  female
##  4 Adelie  &amp;lt;NA&amp;gt;  
##  5 Adelie  female
##  6 Adelie  male  
##  7 Adelie  female
##  8 Adelie  male  
##  9 Adelie  &amp;lt;NA&amp;gt;  
## 10 Adelie  &amp;lt;NA&amp;gt;  
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is also possible to select variables with a sequence of names:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# select all variables from species to sex
dat |&amp;gt;
  select(species:sex)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 3
##    species body_mass_g sex   
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt; 
##  1 Adelie         3750 male  
##  2 Adelie         3800 female
##  3 Adelie         3250 female
##  4 Adelie           NA &amp;lt;NA&amp;gt;  
##  5 Adelie         3450 female
##  6 Adelie         3650 male  
##  7 Adelie         3625 female
##  8 Adelie         4675 male  
##  9 Adelie         3475 &amp;lt;NA&amp;gt;  
## 10 Adelie         4250 &amp;lt;NA&amp;gt;  
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Last but not least, &lt;code&gt;select()&lt;/code&gt; can also be used as an easy way to rearrange columns in the desired order:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# put sex as first column, then all the others
dat |&amp;gt;
  select(sex, species:year)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 4
##    sex    species body_mass_g  year
##    &amp;lt;fct&amp;gt;  &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;int&amp;gt;
##  1 male   Adelie         3750  2007
##  2 female Adelie         3800  2007
##  3 female Adelie         3250  2007
##  4 &amp;lt;NA&amp;gt;   Adelie           NA  2007
##  5 female Adelie         3450  2007
##  6 male   Adelie         3650  2007
##  7 female Adelie         3625  2007
##  8 male   Adelie         4675  2007
##  9 &amp;lt;NA&amp;gt;   Adelie         3475  2007
## 10 &amp;lt;NA&amp;gt;   Adelie         4250  2007
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;rename-variables&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Rename variables&lt;/h2&gt;
&lt;p&gt;To rename variables, use the &lt;code&gt;rename()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# rename variables
dat |&amp;gt;
  rename(
    body_mass = body_mass_g, # rename body_mass_g into body_mass
    study_year = year # rename year into study_year
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 4
##    species body_mass sex    study_year
##    &amp;lt;fct&amp;gt;       &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;       &amp;lt;int&amp;gt;
##  1 Adelie       3750 male         2007
##  2 Adelie       3800 female       2007
##  3 Adelie       3250 female       2007
##  4 Adelie         NA &amp;lt;NA&amp;gt;         2007
##  5 Adelie       3450 female       2007
##  6 Adelie       3650 male         2007
##  7 Adelie       3625 female       2007
##  8 Adelie       4675 male         2007
##  9 Adelie       3475 &amp;lt;NA&amp;gt;         2007
## 10 Adelie       4250 &amp;lt;NA&amp;gt;         2007
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This might not be intuitive (at least it was not for me at the time of learning this package), so bear in mind that you always need to write first the new name and then the old name (separated with the &lt;code&gt;=&lt;/code&gt; sign).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;create-or-modify-variables&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Create or modify variables&lt;/h2&gt;
&lt;p&gt;You can create or modify certain variables of the data frame with &lt;code&gt;mutate()&lt;/code&gt;, based on:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;another variable, or&lt;/li&gt;
&lt;li&gt;a vector of your choice.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# create a new variable based on an existing one
dat |&amp;gt;
  mutate(
    body_mass_kg = body_mass_g / 1000
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 5
##    species body_mass_g sex     year body_mass_kg
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt;        &amp;lt;dbl&amp;gt;
##  1 Adelie         3750 male    2007         3.75
##  2 Adelie         3800 female  2007         3.8 
##  3 Adelie         3250 female  2007         3.25
##  4 Adelie           NA &amp;lt;NA&amp;gt;    2007        NA   
##  5 Adelie         3450 female  2007         3.45
##  6 Adelie         3650 male    2007         3.65
##  7 Adelie         3625 female  2007         3.62
##  8 Adelie         4675 male    2007         4.68
##  9 Adelie         3475 &amp;lt;NA&amp;gt;    2007         3.48
## 10 Adelie         4250 &amp;lt;NA&amp;gt;    2007         4.25
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# create a new variable from a vector of your choice
dat |&amp;gt;
  mutate(
    ID = 1:nrow(dat)
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 5
##    species body_mass_g sex     year    ID
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt; &amp;lt;int&amp;gt;
##  1 Adelie         3750 male    2007     1
##  2 Adelie         3800 female  2007     2
##  3 Adelie         3250 female  2007     3
##  4 Adelie           NA &amp;lt;NA&amp;gt;    2007     4
##  5 Adelie         3450 female  2007     5
##  6 Adelie         3650 male    2007     6
##  7 Adelie         3625 female  2007     7
##  8 Adelie         4675 male    2007     8
##  9 Adelie         3475 &amp;lt;NA&amp;gt;    2007     9
## 10 Adelie         4250 &amp;lt;NA&amp;gt;    2007    10
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that if you create a variable with a name which already exists in the data frame, the old variable will be erased and replaced by the new one.&lt;/p&gt;
&lt;p&gt;Like &lt;code&gt;rename()&lt;/code&gt;, &lt;code&gt;mutate()&lt;/code&gt; requires the argument to be written as &lt;code&gt;name = expression&lt;/code&gt;, where &lt;code&gt;name&lt;/code&gt; is name of the column created or modified and &lt;code&gt;expression&lt;/code&gt; is the formula for calculating the values.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;summarize-observations&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Summarize observations&lt;/h2&gt;
&lt;p&gt;Often, you will want to summarize the data with some &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt;. This can be done with the &lt;code&gt;summarize()&lt;/code&gt; function, in addition to most functions used for descriptive statistics (&lt;code&gt;mean()&lt;/code&gt;, &lt;code&gt;median()&lt;/code&gt;, &lt;code&gt;min()&lt;/code&gt;, &lt;code&gt;max()&lt;/code&gt;, &lt;code&gt;sd()&lt;/code&gt;, &lt;code&gt;var()&lt;/code&gt;, etc.):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# compute mean and sd of body mass
dat |&amp;gt;
  summarize(
    body_mass_mean = mean(body_mass_g, na.rm = TRUE),
    body_mass_sd = sd(body_mass_g, na.rm = TRUE)
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 1 × 2
##   body_mass_mean body_mass_sd
##            &amp;lt;dbl&amp;gt;        &amp;lt;dbl&amp;gt;
## 1          4202.         802.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;na.rm = TRUE&lt;/code&gt; argument is used to omit missing values in the computation of the summary statistics.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;summarize()&lt;/code&gt; and &lt;code&gt;summarise()&lt;/code&gt; give the exact same results.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;identify-distinct-values&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Identify distinct values&lt;/h2&gt;
&lt;p&gt;Identifying distinct values of a variable can be done with &lt;code&gt;distinct()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# find the distinct species
dat |&amp;gt;
  distinct(species)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 1
##   species  
##   &amp;lt;fct&amp;gt;    
## 1 Adelie   
## 2 Gentoo   
## 3 Chinstrap&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Identifying distinct values is mostly done on qualitative or quantitative discrete variables, but it can be done on any type of variable and with several variables at the same time. If more than one variables is specified, it returns all the combinations of values of the variables.&lt;/p&gt;
&lt;p&gt;For instance, with species and study year:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# combination of distinct species and year
dat |&amp;gt;
  distinct(species, year)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 9 × 2
##   species    year
##   &amp;lt;fct&amp;gt;     &amp;lt;int&amp;gt;
## 1 Adelie     2007
## 2 Adelie     2008
## 3 Adelie     2009
## 4 Gentoo     2007
## 5 Gentoo     2008
## 6 Gentoo     2009
## 7 Chinstrap  2007
## 8 Chinstrap  2008
## 9 Chinstrap  2009&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;connected-operations&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Connected operations&lt;/h2&gt;
&lt;p&gt;Another advantage of using the &lt;code&gt;{dplyr}&lt;/code&gt; package is that several operations can be connected all at once, with great readability of the code. This can easily be done with the pipe operator (&lt;code&gt;|&amp;gt;&lt;/code&gt; or &lt;code&gt;%&amp;gt;%&lt;/code&gt;) introduced earlier.&lt;/p&gt;
&lt;p&gt;Until now, we have always seen the same structure: we call a data frame, and then we apply an operation on that data frame. From now on, we will see how to combine more operations into one single chain of operations.&lt;/p&gt;
&lt;div id=&#34;group-by&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Group by&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;group_by()&lt;/code&gt; allows to modify the way the basic functions are performed. Instead of covering all the rows of the data frame, the operations will cover each of the groups of rows defined by the grouping command. In this way, aggregation operations, using &lt;code&gt;summarize()&lt;/code&gt;, will produce statistics for each group rather than for all observations.&lt;/p&gt;
&lt;p&gt;For example, we might be interested in computing some descriptive statistics of a quantitative variable, for each level of a qualitative variable (so by group).&lt;/p&gt;
&lt;p&gt;In our case, suppose we would like to compute the mean and standard deviation of the body mass, but this time separately for each species:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# compute mean and sd of body mass by species
dat |&amp;gt;
  group_by(species) |&amp;gt; # group by species
  summarize(
    mean = mean(body_mass_g, na.rm = TRUE), # compute mean
    sd = sd(body_mass_g, na.rm = TRUE) # compute sd
  )&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    3701.  459.
## 2 Chinstrap 3733.  384.
## 3 Gentoo    5076.  504.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Applied to the example above, here is how the pipe operator works:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;The first operation (&lt;code&gt;group_by()&lt;/code&gt;) groups observations by species.&lt;/li&gt;
&lt;li&gt;Then the output of the first operation is used as the input for the second operation (&lt;code&gt;summarize()&lt;/code&gt;): mean and standard deviation are computed on body mass.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;As a result, we have the mean and standard deviation of body mass by group. As you can imagine, all previous operations can be connected to match your needs.&lt;/p&gt;
&lt;p&gt;Also note that &lt;code&gt;group_by()&lt;/code&gt; can be used for several grouping variables at the same time:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# compute mean and sd of body mass by species and sex
dat |&amp;gt;
  group_by(species, sex) |&amp;gt; # group by species and sex
  summarize(
    mean = mean(body_mass_g, na.rm = TRUE), # compute mean
    sd = sd(body_mass_g, na.rm = TRUE) # compute sd
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 8 × 4
## # Groups:   species [3]
##   species   sex     mean    sd
##   &amp;lt;fct&amp;gt;     &amp;lt;fct&amp;gt;  &amp;lt;dbl&amp;gt; &amp;lt;dbl&amp;gt;
## 1 Adelie    female 3369.  269.
## 2 Adelie    male   4043.  347.
## 3 Adelie    &amp;lt;NA&amp;gt;   3540   477.
## 4 Chinstrap female 3527.  285.
## 5 Chinstrap male   3939.  362.
## 6 Gentoo    female 4680.  282.
## 7 Gentoo    male   5485.  313.
## 8 Gentoo    &amp;lt;NA&amp;gt;   4588.  338.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;(Note that, as for all connected operations, the name of the data frame needs to be specified only in the first operation.)&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;number-of-observations&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Number of observations&lt;/h3&gt;
&lt;p&gt;Some operations can only be performed inside other operations.&lt;/p&gt;
&lt;p&gt;This is the case with the number of observations &lt;code&gt;n()&lt;/code&gt;, which can only be used inside &lt;code&gt;summarize()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# number of observations
dat |&amp;gt;
  summarize(n_obs = n())&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 1 × 1
##   n_obs
##   &amp;lt;int&amp;gt;
## 1   344&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To refer with the previous connected operation &lt;code&gt;group_by()&lt;/code&gt;, we can compute the number of observations by group using the two operations &lt;code&gt;n()&lt;/code&gt; and &lt;code&gt;group_by()&lt;/code&gt; separated by the pipe operator:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# number of observations by species
dat |&amp;gt;
  group_by(species) |&amp;gt;
  summarize(n_obs = n())&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 2
##   species   n_obs
##   &amp;lt;fct&amp;gt;     &amp;lt;int&amp;gt;
## 1 Adelie      152
## 2 Chinstrap    68
## 3 Gentoo      124&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that &lt;code&gt;n()&lt;/code&gt; accepts no parameters and is therefore always written with empty parentheses.&lt;/p&gt;
&lt;p&gt;Moreover, note also that the &lt;code&gt;count()&lt;/code&gt; function is equivalent to &lt;code&gt;summarize(n = n())&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# number of observations
dat |&amp;gt;
  count()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 1 × 1
##       n
##   &amp;lt;int&amp;gt;
## 1   344&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# number of observations by species
dat |&amp;gt;
  count(species)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 2
##   species       n
##   &amp;lt;fct&amp;gt;     &amp;lt;int&amp;gt;
## 1 Adelie      152
## 2 Chinstrap    68
## 3 Gentoo      124&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;number-of-distinct-values&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Number of distinct values&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;n_distinct()&lt;/code&gt;, which can also be used only inside &lt;code&gt;summarize()&lt;/code&gt;, computes the number of different values/levels of a variable or combination of variables:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# number of distinct species
dat |&amp;gt;
  summarize(n_species = n_distinct(species))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 1 × 1
##   n_species
##       &amp;lt;int&amp;gt;
## 1         3&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# number of distinct species and year of study
dat |&amp;gt;
  summarize(n_species_year = n_distinct(species, year))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 1 × 1
##   n_species_year
##            &amp;lt;int&amp;gt;
## 1              9&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that you do not have to specify a name for the output. In that case, the name of the operation will be used. For example:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# number of distinct species
dat |&amp;gt;
  summarize(n_distinct(species))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 1 × 1
##   `n_distinct(species)`
##                   &amp;lt;int&amp;gt;
## 1                     3&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;first-last-or-nth-value&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;First, last or nth value&lt;/h3&gt;
&lt;p&gt;Also only available inside &lt;code&gt;summarize()&lt;/code&gt;, the first, last or nth value can be found with the following commands:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# first value of the variable sex
dat |&amp;gt;
  summarize(first(sex))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 1 × 1
##   `first(sex)`
##   &amp;lt;fct&amp;gt;       
## 1 male&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# last value of the variable sex
dat |&amp;gt;
  summarize(last(sex))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 1 × 1
##   `last(sex)`
##   &amp;lt;fct&amp;gt;      
## 1 female&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# 37th value of the variable sex
dat |&amp;gt;
  summarize(nth(sex, n = 37))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 1 × 1
##   `nth(sex, n = 37)`
##   &amp;lt;fct&amp;gt;             
## 1 male&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Several interesting arguments exist within this function to deal with missing values. For the interested reader, see more information in the documentation of the function (run &lt;code&gt;?nth()&lt;/code&gt;).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;if-else&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;If else&lt;/h3&gt;
&lt;p&gt;A very common data transformation is the well known “if else” technique. This technique is usually used to create, from an existing variable, another variable which can take &lt;strong&gt;two levels&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Suppose that we want to create a new variable called &lt;code&gt;body_mass_cat&lt;/code&gt;, which takes the value “High” when &lt;code&gt;body_mass_g&lt;/code&gt; is equal or greater than a certain threshold, “Low” otherwise. This transformation can be performed with the combination of &lt;code&gt;mutate()&lt;/code&gt; and &lt;code&gt;if_else()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# if else
dat |&amp;gt;
  mutate(
    body_mass_cat = if_else(body_mass_g &amp;gt;= 4000, # condition
      &amp;quot;High&amp;quot;, # output if condition is true
      &amp;quot;Low&amp;quot; # output if condition is false
    )
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 5
##    species body_mass_g sex     year body_mass_cat
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt; &amp;lt;chr&amp;gt;        
##  1 Adelie         3750 male    2007 Low          
##  2 Adelie         3800 female  2007 Low          
##  3 Adelie         3250 female  2007 Low          
##  4 Adelie           NA &amp;lt;NA&amp;gt;    2007 &amp;lt;NA&amp;gt;         
##  5 Adelie         3450 female  2007 Low          
##  6 Adelie         3650 male    2007 Low          
##  7 Adelie         3625 female  2007 Low          
##  8 Adelie         4675 male    2007 High         
##  9 Adelie         3475 &amp;lt;NA&amp;gt;    2007 Low          
## 10 Adelie         4250 &amp;lt;NA&amp;gt;    2007 High         
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;if_else()&lt;/code&gt; function works with 3 arguments:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;The condition (in our case: &lt;code&gt;body_mass_g &amp;gt;= 4000&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;The output value when the condition is true (&lt;code&gt;High&lt;/code&gt; in our case).&lt;/li&gt;
&lt;li&gt;The output value when the conditions is false (&lt;code&gt;Low&lt;/code&gt; in our case).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;As you can see from the table above, when body mass is missing, &lt;code&gt;if_else()&lt;/code&gt; also returns a missing value, which is often a good thing to prevent observations being classified erroneously.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;case-when&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Case when&lt;/h3&gt;
&lt;p&gt;If you want to categorize a variable into &lt;strong&gt;more than two levels&lt;/strong&gt;, an if else is not the most appropriate tool. In these cases, a “case when” is more appropriate.&lt;/p&gt;
&lt;p&gt;For your information, when I learned R, I used to write nested if else functions, that is, a secondary if else inside a primary if else. Most of the time it worked (with very often a waste of time trying to debug my code), but it is very easy to make a mistake. And even if you managed to make it work, the code is not easy to read at all!&lt;/p&gt;
&lt;p&gt;So I highly recommend using this case when technique instead of several if else functions nested within each other.&lt;/p&gt;
&lt;p&gt;Suppose we want to classify body mass into 3 categories: low, medium and high. For this illustration, we arbitrarily decide that body mass is low when it is strictly lower than 3500, high when it is strictly higher than 4750 and medium otherwise.&lt;/p&gt;
&lt;p&gt;With nested if else functions, here is the code we would need to write:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# nested if else
dat |&amp;gt;
  mutate(
    body_mass_cat = if_else(body_mass_g &amp;lt; 3500, # first condition
      &amp;quot;Low&amp;quot;, # output if first condition is true
      if_else(body_mass_g &amp;gt; 4750, # second condition when first condition is false
        &amp;quot;High&amp;quot;, # output when second condition is true
        &amp;quot;Medium&amp;quot; # output when second condition is false
      )
    )
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 5
##    species body_mass_g sex     year body_mass_cat
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt; &amp;lt;chr&amp;gt;        
##  1 Adelie         3750 male    2007 Medium       
##  2 Adelie         3800 female  2007 Medium       
##  3 Adelie         3250 female  2007 Low          
##  4 Adelie           NA &amp;lt;NA&amp;gt;    2007 &amp;lt;NA&amp;gt;         
##  5 Adelie         3450 female  2007 Low          
##  6 Adelie         3650 male    2007 Medium       
##  7 Adelie         3625 female  2007 Medium       
##  8 Adelie         4675 male    2007 Medium       
##  9 Adelie         3475 &amp;lt;NA&amp;gt;    2007 Low          
## 10 Adelie         4250 &amp;lt;NA&amp;gt;    2007 Medium       
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This code works as follows:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;It evaluates the first condition &lt;code&gt;body_mass_g &amp;lt; 3500&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If it is true, &lt;code&gt;body_mass_cat&lt;/code&gt; is &lt;code&gt;Low&lt;/code&gt;. On the contrary, if it is false, it evaluates the second condition &lt;code&gt;body_mass_g &amp;gt; 4750&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If this second condition is true, &lt;code&gt;body_mass_cat&lt;/code&gt; is &lt;code&gt;High&lt;/code&gt;, otherwise it is &lt;code&gt;Medium&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;As you can see from the results above, it works. However, you will concede that it is easy to make coding mistakes, and that the code is not easy to write nor to read.&lt;/p&gt;
&lt;p&gt;To improve this workflow, we now use the case when technique:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# case when, without a default option
dat |&amp;gt;
  mutate(
    body_mass_cat = case_when(
      body_mass_g &amp;lt; 3500 ~ &amp;quot;Low&amp;quot;,
      body_mass_g &amp;gt;= 3500 &amp;amp; body_mass_g &amp;lt;= 4750 ~ &amp;quot;Medium&amp;quot;,
      body_mass_g &amp;gt; 4750 ~ &amp;quot;High&amp;quot;
    )
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 5
##    species body_mass_g sex     year body_mass_cat
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt; &amp;lt;chr&amp;gt;        
##  1 Adelie         3750 male    2007 Medium       
##  2 Adelie         3800 female  2007 Medium       
##  3 Adelie         3250 female  2007 Low          
##  4 Adelie           NA &amp;lt;NA&amp;gt;    2007 &amp;lt;NA&amp;gt;         
##  5 Adelie         3450 female  2007 Low          
##  6 Adelie         3650 male    2007 Medium       
##  7 Adelie         3625 female  2007 Medium       
##  8 Adelie         4675 male    2007 Medium       
##  9 Adelie         3475 &amp;lt;NA&amp;gt;    2007 Low          
## 10 Adelie         4250 &amp;lt;NA&amp;gt;    2007 Medium       
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This workflow is much simpler to code and read!&lt;/p&gt;
&lt;p&gt;If there are no missing values in the variable(s) used for the condition(s), it can even be simplified to:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# case when, with a default option
dat |&amp;gt;
  mutate(
    body_mass_cat = case_when(
      body_mass_g &amp;lt; 3500 ~ &amp;quot;Low&amp;quot;,
      body_mass_g &amp;gt; 4750 ~ &amp;quot;High&amp;quot;,
      .default = &amp;quot;Medium&amp;quot; # default output
    )
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 5
##    species body_mass_g sex     year body_mass_cat
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt; &amp;lt;chr&amp;gt;        
##  1 Adelie         3750 male    2007 Medium       
##  2 Adelie         3800 female  2007 Medium       
##  3 Adelie         3250 female  2007 Low          
##  4 Adelie           NA &amp;lt;NA&amp;gt;    2007 Medium       
##  5 Adelie         3450 female  2007 Low          
##  6 Adelie         3650 male    2007 Medium       
##  7 Adelie         3625 female  2007 Medium       
##  8 Adelie         4675 male    2007 Medium       
##  9 Adelie         3475 &amp;lt;NA&amp;gt;    2007 Low          
## 10 Adelie         4250 &amp;lt;NA&amp;gt;    2007 Medium       
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, a default output can be specified with &lt;code&gt;.default&lt;/code&gt; for observations that do not match any of the conditions.&lt;/p&gt;
&lt;p&gt;However, be careful if there are missing values! Indeed, if there is at least one missing value (as in our case), the code above is not correct because observations with missing &lt;code&gt;body_mass_g&lt;/code&gt; will be misclassified as &lt;code&gt;Medium&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Therefore, if you really want to specify a default output, I recommend using the code below which keeps missing values as &lt;code&gt;NA&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# case when, with a default option and missing values
dat |&amp;gt;
  mutate(
    body_mass_cat = case_when(
      body_mass_g &amp;lt; 3500 ~ &amp;quot;Low&amp;quot;,
      body_mass_g &amp;gt; 4750 ~ &amp;quot;High&amp;quot;,
      is.na(body_mass_g) ~ NA, # keep missing values as NA
      .default = &amp;quot;Medium&amp;quot; # default output
    )
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 344 × 5
##    species body_mass_g sex     year body_mass_cat
##    &amp;lt;fct&amp;gt;         &amp;lt;int&amp;gt; &amp;lt;fct&amp;gt;  &amp;lt;int&amp;gt; &amp;lt;chr&amp;gt;        
##  1 Adelie         3750 male    2007 Medium       
##  2 Adelie         3800 female  2007 Medium       
##  3 Adelie         3250 female  2007 Low          
##  4 Adelie           NA &amp;lt;NA&amp;gt;    2007 &amp;lt;NA&amp;gt;         
##  5 Adelie         3450 female  2007 Low          
##  6 Adelie         3650 male    2007 Medium       
##  7 Adelie         3625 female  2007 Medium       
##  8 Adelie         4675 male    2007 Medium       
##  9 Adelie         3475 &amp;lt;NA&amp;gt;    2007 Low          
## 10 Adelie         4250 &amp;lt;NA&amp;gt;    2007 Medium       
## # ℹ 334 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I personally prefer to write all categories and not write a default option for improved code readability and robustness of my code, but it is more a personal opinion.&lt;/p&gt;
&lt;p&gt;In all cases, no matter if you used an if else or a case when, it is a good practice to check the variable you just created to make sure that you obtain the intended results.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion-and-other-resources&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion and other resources&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;This article introduced and illustrated the most common data manipulation and data management tools in R, using the &lt;code&gt;{dplyr}&lt;/code&gt; package. We also introduced the pipe operator, well known to users of modern R packages.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;{dplyr}&lt;/code&gt; package offers many more functions for data manipulation (in particular to merge data frames with the family of &lt;code&gt;join()&lt;/code&gt; functions). If you would like to learn more about this package, I recommend starting with the following resources:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;https://dplyr.tidyverse.org/&#34; target=&#34;_blank&#34;&gt;dplyr.tidyverse.org&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://r4ds.hadley.nz/data-transform.html&#34; target=&#34;_blank&#34;&gt;Chapter “Data transformation”&lt;/a&gt; in the book “R for Data Science”&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://github.com/rstudio/cheatsheets/blob/main/data-transformation.pdf&#34; target=&#34;_blank&#34;&gt;Cheatsheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://dplyr.tidyverse.org/articles/dplyr.html&#34; target=&#34;_blank&#34;&gt;Vignette&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;For those who are used to base R, a &lt;a href=&#34;https://cran.r-project.org/web/packages/dplyr/vignettes/base.html&#34; target=&#34;_blank&#34;&gt;vignette&lt;/a&gt; comparing &lt;code&gt;{dplyr}&lt;/code&gt; functions to their base R equivalents&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-palmerpenguins2020horst&#34; class=&#34;csl-entry&#34;&gt;
Horst, Allison Marie, Alison Presmanes Hill, and Kristen B Gorman. 2020. &lt;em&gt;Palmerpenguins: Palmer Archipelago (Antarctica) Penguin Data&lt;/em&gt;. &lt;a href=&#34;https://doi.org/10.5281/zenodo.3960218&#34;&gt;https://doi.org/10.5281/zenodo.3960218&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;The keyboard shortcut for the pipe operator is &lt;code&gt;ctrl + shift + m&lt;/code&gt; (Windows) or &lt;code&gt;cmd + shift + m&lt;/code&gt; (Mac). It will print &lt;code&gt;%&amp;gt;%&lt;/code&gt;, unless you specified to use the native pipe operator &lt;code&gt;|&amp;gt;&lt;/code&gt; in the settings of RStudio.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Pearson, Spearman and Kendall correlation coefficients by hand</title>
      <link>https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/</link>
      <pubDate>Tue, 05 Sep 2023 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/</guid>
      <description>
&lt;script src=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/htmlwidgets/htmlwidgets.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/datatables-css/datatables-crosstalk.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/datatables-binding/datatables.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/jquery/jquery-3.6.0.min.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/dt-core/css/jquery.dataTables.min.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;link href=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/dt-core/css/jquery.dataTables.extra.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/dt-core/js/jquery.dataTables.min.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/crosstalk/css/crosstalk.min.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/index_files/crosstalk/js/crosstalk.min.js&#34;&gt;&lt;/script&gt;

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

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

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

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

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

&lt;p&gt;&lt;img src=&#34;images/how-to-one-way-anova-by-hand.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;An ANOVA is a statistical test used to compare a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#quantitative&#34;&gt;quantitative variable&lt;/a&gt; between groups, to determine if there is a statistically significant difference between several population means. In practice, it is usually used to compare three or more groups. However, in theory, it can also be done with only two groups.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In a previous post, we showed how to perform a &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;one-way ANOVA in R&lt;/a&gt;. In this post, we illustrate how to conduct a one-way ANOVA by hand, via what is usually called an “ANOVA table”.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;data-and-hypotheses&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Data and hypotheses&lt;/h1&gt;
&lt;p&gt;To illustrate the method, suppose we take a &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;sample&lt;/a&gt; of 12 students, divided equally into three classes (A, B and C) and we observe their age. Here is the sample:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-1&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-1&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[24,31,26,23],[24,21,19,24],[15,21,18,18]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;A&lt;\/th&gt;\n      &lt;th&gt;B&lt;\/th&gt;\n      &lt;th&gt;C&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[0,1,2]},{&#34;name&#34;:&#34;A&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;B&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;C&#34;,&#34;targets&#34;:2}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;We are interested in comparing the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;population&lt;/a&gt; means between classes.&lt;/p&gt;
&lt;p&gt;Remember that the null hypothesis of the ANOVA is that all means are equal (i.e., age is not significantly different between classes), whereas the alternative hypothesis is that at least one mean is different from the other two (i.e., age is significantly different in at least one class compared to the other two). Formally, we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\mu_A = \mu_B = \mu_C\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;at least one mean is different&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;anova-by-hand&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;ANOVA by hand&lt;/h1&gt;
&lt;p&gt;As mentioned above, we are going to do an ANOVA table to conclude the test.&lt;/p&gt;
&lt;p&gt;Note that the ANOVA requires some assumptions (i.e., independence, equality of variances and normality). The aim of this post is to illustrate how to do an ANOVA by hand and not how to verify these assumptions, so we suppose they are met without any verification. See how to &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/#underlying-assumptions-of-anova&#34;&gt;test these assumptions in R&lt;/a&gt; if you are interested.&lt;/p&gt;
&lt;div id=&#34;overall-and-group-means&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Overall and group means&lt;/h2&gt;
&lt;p&gt;We first need to compute the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#mean&#34;&gt;mean&lt;/a&gt; age by class (referred as the group means):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;class A: &lt;span class=&#34;math inline&#34;&gt;\(\frac{24 + 31 + 26 + 23}{4} = 26\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;class B: &lt;span class=&#34;math inline&#34;&gt;\(\frac{24 + 21 + 19 + 24}{4} = 22\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;class C: &lt;span class=&#34;math inline&#34;&gt;\(\frac{15 + 21 + 18 + 18}{4} = 18\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;and the mean age for the whole sample (referred as the overall mean):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{equation}
\begin{split}
&amp;amp;       \frac{24 + 31 + 26 + 23 + 24 + 21 + 19 }{12}    \\
&amp;amp;\frac{+ 24 + 15 + 21 + 18 + 18}{12} = 22
\end{split}
\end{equation}
\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;ssr-and-sse&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;SSR and SSE&lt;/h2&gt;
&lt;p&gt;We then need to compute the sum of squares regression (SSR), and the sum of squares error (SSE).&lt;/p&gt;
&lt;p&gt;The SSR is computed by taking the square of the difference between the mean group and the overall mean, multiplied by the number of observations in the group:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-2&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-2&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[&#34;4 * ((26 - 22)^2) = 64&#34;],[&#34;4 * ((22 - 22)^2) = 0&#34;],[&#34;4 * ((18 - 22)^2) = 64&#34;]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;A&lt;\/th&gt;\n      &lt;th&gt;B&lt;\/th&gt;\n      &lt;th&gt;C&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;name&#34;:&#34;A&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;B&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;C&#34;,&#34;targets&#34;:2}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;and then taking the sum of all cells:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[64+0+64 = 128 = SSR\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The SSE is computed by taking the square of the difference between each observation and its group mean:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-3&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-3&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[&#34;(24 - 26)^2 = 4&#34;,&#34;(31 - 26)^2 = 25&#34;,&#34;(26 - 26)^2 = 0&#34;,&#34;(23 - 26)^2 = 9&#34;],[&#34;(24 - 22)^2 = 4&#34;,&#34;(21 - 22)^2 = 1&#34;,&#34;(19 - 22)^2 = 9&#34;,&#34;(24 - 22)^2 = 4&#34;],[&#34;(15 - 18)^2 = 9&#34;,&#34;(21 - 18)^2 = 9&#34;,&#34;(18 - 18)^2 = 0&#34;,&#34;(18 - 18)^2 = 0&#34;]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;A&lt;\/th&gt;\n      &lt;th&gt;B&lt;\/th&gt;\n      &lt;th&gt;C&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;name&#34;:&#34;A&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;B&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;C&#34;,&#34;targets&#34;:2}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;and then taking the sum of all cells:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{equation}
\begin{split}
&amp;amp; 4+25+0+9+4+1+9+4    \\
&amp;amp; +9+9+0+0 = 74 = SSE
\end{split}
\end{equation}
\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For those interested in computing the sum of square total (SST), it is simply the sum of SSR and SSE, that is,&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{equation}
\begin{split}
SST &amp;amp;= SSR + SSE\\
&amp;amp;= 128 + 74 \\
&amp;amp; =202
\end{split}
\end{equation}
\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;anova-table&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;ANOVA table&lt;/h2&gt;
&lt;p&gt;The ANOVA table looks as follows (we leave it empty and we are going to fill it in step by step):&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-4&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-4&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[&#34;Regression&#34;,&#34;Error&#34;],[null,null],[null,null],[null,null],[null,null]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Type&lt;\/th&gt;\n      &lt;th&gt;Sum.of.Sq.&lt;\/th&gt;\n      &lt;th&gt;Df&lt;\/th&gt;\n      &lt;th&gt;Mean.Sq.&lt;\/th&gt;\n      &lt;th&gt;F.value&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;name&#34;:&#34;Type&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;Sum.of.Sq.&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;Df&#34;,&#34;targets&#34;:2},{&#34;name&#34;:&#34;Mean.Sq.&#34;,&#34;targets&#34;:3},{&#34;name&#34;:&#34;F.value&#34;,&#34;targets&#34;:4}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;We start to build the ANOVA table by plugging the SSR and SSE values found above into the table (in the “Sum.of.Sq.” column):&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-5&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-5&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[&#34;Regression&#34;,&#34;Error&#34;],[128,74],[null,null],[null,null],[null,null]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Type&lt;\/th&gt;\n      &lt;th&gt;Sum.of.Sq.&lt;\/th&gt;\n      &lt;th&gt;Df&lt;\/th&gt;\n      &lt;th&gt;Mean.Sq.&lt;\/th&gt;\n      &lt;th&gt;F.value&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;Type&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;Sum.of.Sq.&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;Df&#34;,&#34;targets&#34;:2},{&#34;name&#34;:&#34;Mean.Sq.&#34;,&#34;targets&#34;:3},{&#34;name&#34;:&#34;F.value&#34;,&#34;targets&#34;:4}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The “Df” column corresponds to the degrees of freedom, and is computed as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;for the line regression: number of groups - 1 = 3 - 1 = 2&lt;/li&gt;
&lt;li&gt;for the line error: number of observations - number of groups = 12 - 3 = 9&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;With this information, the ANOVA table becomes:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-6&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-6&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[&#34;Regression&#34;,&#34;Error&#34;],[128,74],[2,9],[null,null],[null,null]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Type&lt;\/th&gt;\n      &lt;th&gt;Sum.of.Sq.&lt;\/th&gt;\n      &lt;th&gt;Df&lt;\/th&gt;\n      &lt;th&gt;Mean.Sq.&lt;\/th&gt;\n      &lt;th&gt;F.value&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[1,2]},{&#34;name&#34;:&#34;Type&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;Sum.of.Sq.&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;Df&#34;,&#34;targets&#34;:2},{&#34;name&#34;:&#34;Mean.Sq.&#34;,&#34;targets&#34;:3},{&#34;name&#34;:&#34;F.value&#34;,&#34;targets&#34;:4}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The “Mean.Sq.” column corresponds to the Mean Square, and is equal to the sum of square divided by the degrees of freedom, so the “Sum.of.Sq.” column divided by the “Df” column:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-7&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-7&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[&#34;Regression&#34;,&#34;Error&#34;],[128,74],[2,9],[64,8.222],[null,null]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Type&lt;\/th&gt;\n      &lt;th&gt;Sum.of.Sq.&lt;\/th&gt;\n      &lt;th&gt;Df&lt;\/th&gt;\n      &lt;th&gt;Mean.Sq.&lt;\/th&gt;\n      &lt;th&gt;F.value&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[1,2,3]},{&#34;name&#34;:&#34;Type&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;Sum.of.Sq.&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;Df&#34;,&#34;targets&#34;:2},{&#34;name&#34;:&#34;Mean.Sq.&#34;,&#34;targets&#34;:3},{&#34;name&#34;:&#34;F.value&#34;,&#34;targets&#34;:4}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Finally, the F-value corresponds to the ratio between the two mean squares, so &lt;span class=&#34;math inline&#34;&gt;\(\frac{64}{8.222} = 7.78\)&lt;/span&gt;:&lt;/p&gt;
&lt;div class=&#34;datatables html-widget html-fill-item&#34; id=&#34;htmlwidget-8&#34; style=&#34;width:100%;height:auto;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-8&#34;&gt;{&#34;x&#34;:{&#34;filter&#34;:&#34;none&#34;,&#34;vertical&#34;:false,&#34;data&#34;:[[&#34;Regression&#34;,&#34;Error&#34;],[128,74],[2,9],[64,8.222],[7.78,null]],&#34;container&#34;:&#34;&lt;table class=\&#34;display\&#34;&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th&gt;Type&lt;\/th&gt;\n      &lt;th&gt;Sum.of.Sq.&lt;\/th&gt;\n      &lt;th&gt;Df&lt;\/th&gt;\n      &lt;th&gt;Mean.Sq.&lt;\/th&gt;\n      &lt;th&gt;F.value&lt;\/th&gt;\n    &lt;\/tr&gt;\n  &lt;\/thead&gt;\n&lt;\/table&gt;&#34;,&#34;options&#34;:{&#34;dom&#34;:&#34;t&#34;,&#34;columnDefs&#34;:[{&#34;className&#34;:&#34;dt-right&#34;,&#34;targets&#34;:[1,2,3,4]},{&#34;name&#34;:&#34;Type&#34;,&#34;targets&#34;:0},{&#34;name&#34;:&#34;Sum.of.Sq.&#34;,&#34;targets&#34;:1},{&#34;name&#34;:&#34;Df&#34;,&#34;targets&#34;:2},{&#34;name&#34;:&#34;Mean.Sq.&#34;,&#34;targets&#34;:3},{&#34;name&#34;:&#34;F.value&#34;,&#34;targets&#34;:4}],&#34;order&#34;:[],&#34;autoWidth&#34;:false,&#34;orderClasses&#34;:false}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;This F-value gives the test statistic (also referred as &lt;span class=&#34;math inline&#34;&gt;\(F_{obs}\)&lt;/span&gt;), which needs to be compared with the critical value found in the Fisher table to conclude the test.&lt;/p&gt;
&lt;p&gt;We find the critical value in the Fisher table based on the degrees of freedom (those used in the ANOVA table) and based on the significance level. Suppose we take a significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 0.05\)&lt;/span&gt;, the critical value can be found in the Fisher table as follows:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;images/anova-by-hand-fisher-table.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;So we have&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[F_{2; 9; 0.05} = 4.26\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;If you are interested to find this value with R, it can be found with the &lt;code&gt;qf()&lt;/code&gt; function, where 0.95 corresponds to &lt;span class=&#34;math inline&#34;&gt;\(1 - \alpha\)&lt;/span&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;qf(0.95, 2, 9)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 4.256495&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion-of-the-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Conclusion of the test&lt;/h2&gt;
&lt;p&gt;The rejection rule says that, if:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(F_{obs} &amp;gt; F_{2; 9; 0.05} \Rightarrow\)&lt;/span&gt; we reject the null hypothesis&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(F_{obs} \le F_{2; 9; 0.05} \Rightarrow\)&lt;/span&gt; we &lt;em&gt;do not&lt;/em&gt; reject the null hypothesis&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In our case,&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[F_{obs} = 7.78 &amp;gt; F_{2; 9; 0.05} = 4.26\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(\Rightarrow\)&lt;/span&gt; We reject the null hypothesis that all means are equal. In other words, it means that at least one class is different than the other two in terms of age.&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;To verify our results, here is the ANOVA table using R:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;##             Df Sum Sq Mean Sq F value Pr(&amp;gt;F)  
## class        2    128   64.00   7.784 0.0109 *
## Residuals    9     74    8.22                 
## ---
## Signif. codes:  0 &amp;#39;***&amp;#39; 0.001 &amp;#39;**&amp;#39; 0.01 &amp;#39;*&amp;#39; 0.05 &amp;#39;.&amp;#39; 0.1 &amp;#39; &amp;#39; 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We found the same results by hand, but note that in R, the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value is computed instead of comparing the &lt;span class=&#34;math inline&#34;&gt;\(F_{obs}\)&lt;/span&gt; with the critical value. The &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value can easily be found in R based on the &lt;span class=&#34;math inline&#34;&gt;\(F_{obs}\)&lt;/span&gt; and the degrees of freedom:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;pf(7.78, 2, 9,
  lower.tail = FALSE
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.010916&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to conduct a one-way ANOVA by hand. See this &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;tutorial&lt;/a&gt; if you want to learn how to do it in R.&lt;/p&gt;
&lt;p&gt;As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;In that case, a &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test&lt;/a&gt; is usually preferred over an ANOVA, although both tests will lead to the exact same conclusions.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Remember that an ANOVA cannot tell you which group is different than the other in terms of the quantitative dependent variable, nor whether they are all different or if only one is different. To answer this question, post-hoc tests are required. This is beyond the scope of the present post, but it can easily be done in R (see this &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;tutorial&lt;/a&gt;).&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Top 10 errors in R and how to fix them</title>
      <link>https://statsandr.com/blog/top-10-errors-in-r/</link>
      <pubDate>Tue, 07 Feb 2023 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/top-10-errors-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;#unmatched-parentheses-curly-braces-square-brackets-or-quotes&#34; id=&#34;toc-unmatched-parentheses-curly-braces-square-brackets-or-quotes&#34;&gt;1. Unmatched parentheses, curly braces, square brackets or quotes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#using-a-function-that-is-not-installed-or-loaded&#34; id=&#34;toc-using-a-function-that-is-not-installed-or-loaded&#34;&gt;2. Using a function that is not installed or loaded&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#typos-in-function-variable-dataset-object-or-package-names&#34; id=&#34;toc-typos-in-function-variable-dataset-object-or-package-names&#34;&gt;3. Typos in function, variable, dataset, object or package names&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#missing-incorrect-or-misspelled-arguments-in-functions&#34; id=&#34;toc-missing-incorrect-or-misspelled-arguments-in-functions&#34;&gt;4. Missing, incorrect or misspelled arguments in functions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#wrong-inappropriate-or-inconsistent-data-types&#34; id=&#34;toc-wrong-inappropriate-or-inconsistent-data-types&#34;&gt;5. Wrong, inappropriate or inconsistent data types&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#forgetting-the-sign-in-ggplot2&#34; id=&#34;toc-forgetting-the-sign-in-ggplot2&#34;&gt;6. Forgetting the + sign in ggplot2&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#misunderstanding-between-and&#34; id=&#34;toc-misunderstanding-between-and&#34;&gt;7. Misunderstanding between = and ==&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#undefined-columns-selected&#34; id=&#34;toc-undefined-columns-selected&#34;&gt;8. Undefined columns selected&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#problem-when-importing-or-using-the-wrong-data-file&#34; id=&#34;toc-problem-when-importing-or-using-the-wrong-data-file&#34;&gt;9. Problem when importing or using the wrong data file&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#problem-when-using-the-operator&#34; id=&#34;toc-problem-when-using-the-operator&#34;&gt;10. Problem when using the $ operator&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#operator-is-invalid-for-atomic-vectors&#34; id=&#34;toc-operator-is-invalid-for-atomic-vectors&#34;&gt;$ operator is invalid for atomic vectors&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#object-of-type-closure-is-not-subsettable&#34; id=&#34;toc-object-of-type-closure-is-not-subsettable&#34;&gt;object of type ‘closure’ is not subsettable&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#warnings&#34; id=&#34;toc-warnings&#34;&gt;Warnings&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#nas-introduced-by-coercion&#34; id=&#34;toc-nas-introduced-by-coercion&#34;&gt;NAs introduced by coercion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#removed-rows-containing-non-finite-values-stat_bin&#34; id=&#34;toc-removed-rows-containing-non-finite-values-stat_bin&#34;&gt;Removed … rows containing non-finite values (stat_bin())&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/top-10-errors-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;If you are just starting with R, you will often encounter errors in your code which prevent it to run. I remember when I was just starting to use R, errors in my code were so frequent that I almost gave up learning this programming language. I even recall that I went back to Excel a few times to finish my analyses because I could not find what was causing the issue.&lt;/p&gt;
&lt;p&gt;Fortunately, I forced myself to continue despite the difficulties of the beginning. And today, even if I still encounter errors almost every time I write R code, with experience and practice, it takes less and less time to fix them. If you are also struggling at the beginning, rest assured, it is normal: everyone experiences some frustration when learning a new programming language (and this is the case not only with R).&lt;/p&gt;
&lt;p&gt;In this post, I highlight the &lt;strong&gt;10 most common errors in R and how to fix them&lt;/strong&gt;. Of course, errors depend on your code and your analyses, so it is impossible to cover all of them (and Google does it way better than me). However, I would like to focus on some common syntax mistakes that are frequent when learning R, and which can sometimes take a long time to be fixed before realizing that the solution is right in front of our eyes.&lt;/p&gt;
&lt;p&gt;This collection is based on my personal experience and the errors encountered by my students when I &lt;a href=&#34;https://antoinesoetewey.com/teaching/&#34;&gt;teach&lt;/a&gt; R. This list being non-exhaustive, feel free to comment (at the end of the post) with errors you often face when using R.&lt;/p&gt;
&lt;p&gt;For each error, I provide examples and solutions to fix them. I also mention a couple of warnings (which are, strictly speaking, not errors) at the end of the post.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;unmatched-parentheses-curly-braces-square-brackets-or-quotes&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;1. Unmatched parentheses, curly braces, square brackets or quotes&lt;/h1&gt;
&lt;p&gt;One rather trivial but still quite frequent error is a missing parenthesis, curly brace, square bracket or quotation mark.&lt;/p&gt;
&lt;p&gt;This type of error is applicable to many programming languages. In R, for instance:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## missing a closing parenthesis:
mean(c(1, 7, 13)
     
## missing a curly brace before &amp;quot;else&amp;quot;:
x &amp;lt;- 7 
if(x &amp;gt; 10) {
  print(&amp;quot;x &amp;gt; 10&amp;quot;)
 else {
  print(&amp;quot;x &amp;lt;= 10&amp;quot;)
 }
  
## missing a square bracket:
summary(ggplot2::diamonds[, &amp;quot;price&amp;quot;)

## missing a closing quote in 2nd element:
grp &amp;lt;- c(&amp;quot;Group 1&amp;quot;, &amp;quot;Group 2) 
grp&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;These errors are easy to detect when the code is basic, but can become much harder to spot with a more complex code, for instance:&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;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(..method.., &amp;quot;, p-value = &amp;quot;, ..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;)
    )
  }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Thankfully, if you use RStudio,&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; a closing parenthesis, curly brace, square bracket or quotation mark will automatically be written when you open one.&lt;/p&gt;
&lt;p&gt;Bear in mind that when installing a package, you &lt;em&gt;must&lt;/em&gt; use (single or double) quotation marks around the package’s name:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## NOT correct:
install.packages(ggplot2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Error in install.packages : object &amp;#39;ggplot2&amp;#39; not found&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Instead, write one of the two following options:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# install.packages(&amp;quot;ggplot2&amp;quot;)

# install.packages(&amp;#39;ggplot2&amp;#39;)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;solution&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Solution&lt;/h3&gt;
&lt;p&gt;The solution of course is to simply match all opening parentheses, curly braces, square brackets and quotation marks with their closing counterparts:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mean(c(1, 7, 13))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 7&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x &amp;lt;- 7
if (x &amp;gt; 10) {
  print(&amp;quot;x &amp;gt; 10&amp;quot;)
} else {
  print(&amp;quot;x &amp;lt;= 10&amp;quot;)
}&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;x &amp;lt;= 10&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(ggplot2::diamonds[, &amp;quot;price&amp;quot;])&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      price      
##  Min.   :  326  
##  1st Qu.:  950  
##  Median : 2401  
##  Mean   : 3933  
##  3rd Qu.: 5324  
##  Max.   :18823&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;grp &amp;lt;- c(&amp;quot;Group 1&amp;quot;, &amp;quot;Group 2&amp;quot;)
grp&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;Group 1&amp;quot; &amp;quot;Group 2&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Also, make sure:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;to correctly place commas:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## NOT correct (misplaced comma):
c(&amp;quot;Group 1,&amp;quot; &amp;quot;Group 2&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Error: unexpected string constant in &amp;quot;c(&amp;quot;Group 1,&amp;quot; &amp;quot;Group 2&amp;quot;&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## also NOT correct (missing comma):
c(&amp;quot;Group 1&amp;quot; &amp;quot;Group 2&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Error: unexpected string constant in &amp;quot;c(&amp;quot;Group 1&amp;quot; &amp;quot;Group 2&amp;quot;&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## correct:
c(&amp;quot;Group 1&amp;quot;, &amp;quot;Group 2&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;you do not mix single and double quotation marks for the same element:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## NOT correct:
c(&amp;quot;Group 1&amp;#39;)

## correct:
c(&amp;quot;Group 1&amp;quot;)

## also correct:
c(&amp;#39;Group 1&amp;#39;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that &lt;code&gt;c(&#39;Group 1&#39;, &#34;Group 2&#34;)&lt;/code&gt; does not throw an error but for consistency, it is not recommended to mix single and double quotes within the same vector.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;using-a-function-that-is-not-installed-or-loaded&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;2. Using a function that is not installed or loaded&lt;/h1&gt;
&lt;p&gt;If you encounter the following error: “Error in … : could not find function ‘…’”, for example:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;images/could-not-find-function-R.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;it means you are trying to use a function belonging to a package which is not yet installed or loaded.&lt;/p&gt;
&lt;div id=&#34;solution-1&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Solution&lt;/h3&gt;
&lt;p&gt;To solve this error, you have to install the package (if it is not installed yet) and load it with the &lt;code&gt;install.packages()&lt;/code&gt; and &lt;code&gt;library()&lt;/code&gt; functions, respectively:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## install package:
install.packages(&amp;quot;ggplot2&amp;quot;)

## load package:
library(ggplot2)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you are not sure about the usage of these two functions, see more details about &lt;a href=&#34;https://statsandr.com/blog/an-efficient-way-to-install-and-load-r-packages/&#34;&gt;installing and loading a package in R&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;typos-in-function-variable-dataset-object-or-package-names&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;3. Typos in function, variable, dataset, object or package names&lt;/h1&gt;
&lt;p&gt;Another common mistake is to misspell a function, a variable, a dataset, an object or a package’s name, for example:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## typo in function name:
maen(c(1, 7, 13))&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Error in maen(c(1, 7, 13)) : could not find function &amp;quot;maen&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## typo in variable name:
summary(ggplot2::diamonds[, &amp;quot;detph&amp;quot;])&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Error: Column `detph` doesn&amp;#39;t exist&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## typo in dataset name:
data &amp;lt;- data.frame(
  x = rnorm(10),
  y = rnorm(10)
)
summary(dta[, 2])&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Error in summary(dta[, 2]) : object &amp;#39;dta&amp;#39; not found&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## typo in object name:
test &amp;lt;- c(1, 7, 13)
mean(tset)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Error in mean(tset) : object &amp;#39;tset&amp;#39; not found&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## typo in package name:
library(&amp;quot;tydiverse&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Error in library(&amp;quot;tydiverse&amp;quot;) : there is no package called ‘tydiverse’&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;solution-2&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Solution&lt;/h3&gt;
&lt;p&gt;Make sure that you correctly spell all your functions, variables, datasets, objects and packages:&lt;/p&gt;
&lt;p&gt;Note that &lt;strong&gt;R is case sensitive&lt;/strong&gt;; &lt;code&gt;mean()&lt;/code&gt; is considered different than &lt;code&gt;Mean()&lt;/code&gt; for R!&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mean(c(1, 7, 13))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 7&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(ggplot2::diamonds[, &amp;quot;depth&amp;quot;])&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      depth      
##  Min.   :43.00  
##  1st Qu.:61.00  
##  Median :61.80  
##  Mean   :61.75  
##  3rd Qu.:62.50  
##  Max.   :79.00&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;data &amp;lt;- data.frame(
  x = rnorm(10),
  y = rnorm(10)
)
data[, 2]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1]  1.3048697  2.2866454 -1.3888607 -0.2787888 -0.1333213  0.6359504
##  [7] -0.2842529 -2.6564554 -2.4404669  1.3201133&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- c(1, 7, 13)
mean(test)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 7&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(tidyverse)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (&amp;lt;http://conflicted.r-lib.org/&amp;gt;) to force all conflicts to become errors&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you are sure that you correctly spelled an object, a function or a dataset but you still have an error stating that “object ‘…’ is not found”, make sure that you defined your object/function/dataset &lt;em&gt;before&lt;/em&gt; calling it!&lt;/p&gt;
&lt;p&gt;It often happens that a student asks me to come to his/her computer because he/she runs the exact same code than me, but cannot make it work. Most of the time, if his/her code is indeed exactly the same than mine, he/she simply has not executed a object/function/dataset before running the code which includes that object/function/dataset. In other words, he/she simply tries to use an undefined object or variable.&lt;/p&gt;
&lt;p&gt;Remember that writing code in a R script (contrarily to the console) does not mean it is compiled. You actually have to run it (by clicking on the Run button or using the keyboard shortcut) in order the code to be executed and used later. If you are still struggling with this, see the &lt;a href=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio/&#34;&gt;basics of R and RStudio&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;missing-incorrect-or-misspelled-arguments-in-functions&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;4. Missing, incorrect or misspelled arguments in functions&lt;/h1&gt;
&lt;p&gt;Most R functions require arguments. For example, the &lt;code&gt;rnorm()&lt;/code&gt; function requires at least the number of observations, specified via the argument &lt;code&gt;n&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Your code will not run if you do not specify compulsory arguments, or if incorrectly specify an argument. Moreover, the result might not be what you expect if you misspell an argument:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## missing compulsory argument:
rnorm()&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Error in rnorm() : argument &amp;quot;n&amp;quot; is missing, with no default&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## incorrect argument:
rnorm(n = 3, var = 1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Error in rnorm(n = 3, var = 1) : unused argument (var = 1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## misspelled argument:
mean(c(1, 7, 13, NA), narm = TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] NA&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The last piece of code does not throw an error, but the result is not what we want.&lt;/p&gt;
&lt;div id=&#34;solution-3&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Solution&lt;/h3&gt;
&lt;p&gt;To solve these errors, make sure to specify &lt;strong&gt;at least all compulsory arguments&lt;/strong&gt; of the function, and the correct ones:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In &lt;code&gt;rnorm()&lt;/code&gt;, it is the standard deviation, &lt;code&gt;sd&lt;/code&gt;, which can be specified in addition to the number of observations &lt;code&gt;n&lt;/code&gt; (instead of the variance &lt;code&gt;var&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Removing &lt;code&gt;NA&lt;/code&gt; is done with &lt;code&gt;na.rm&lt;/code&gt; (instead of &lt;code&gt;narm&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rnorm(n = 3, sd = 1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] -0.3066386 -1.7813084 -0.1719174&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mean(c(1, 7, 13, NA), na.rm = TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 7&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you do not know the arguments of a function by heart, you can always check the documentation with &lt;code&gt;?function_name&lt;/code&gt; or &lt;code&gt;help(function_name)&lt;/code&gt;, for example:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;?rnorm()

## or:
help(rnorm)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;wrong-inappropriate-or-inconsistent-data-types&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;5. Wrong, inappropriate or inconsistent data types&lt;/h1&gt;
&lt;p&gt;There are several &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/&#34;&gt;data types in R&lt;/a&gt;, the main ones being:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Numeric&lt;/li&gt;
&lt;li&gt;Character&lt;/li&gt;
&lt;li&gt;Factor&lt;/li&gt;
&lt;li&gt;Logical&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You know that some operations and analyses are possible and appropriate only with some specific types of data.&lt;/p&gt;
&lt;p&gt;For example, it is not appropriate to compute the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#mean&#34;&gt;mean&lt;/a&gt; of a factor or character variable:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;gender &amp;lt;- factor(c(&amp;quot;female&amp;quot;, &amp;quot;female&amp;quot;, &amp;quot;male&amp;quot;, &amp;quot;female&amp;quot;, &amp;quot;male&amp;quot;))

mean(gender)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Warning in mean.default(gender): argument is not numeric or logical: returning
## NA&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] NA&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Likewise, although it is technically possible, it makes little sense to draw a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#barplot&#34;&gt;barplot&lt;/a&gt; of a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/&#34;&gt;quantitative continuous&lt;/a&gt; variable because in most cases, the frequency will be 1 for each value:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;barplot(table(rnorm(10)))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/top-10-errors-in-r/index_files/figure-html/unnamed-chunk-33-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;(By the way, if your data is not already displayed in the form of a table, do not forget to add &lt;code&gt;table()&lt;/code&gt; inside the &lt;code&gt;barplot()&lt;/code&gt; function.)&lt;/em&gt;&lt;/p&gt;
&lt;div id=&#34;solution-4&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Solution&lt;/h3&gt;
&lt;p&gt;Make sure to use the appropriate operation and type of analysis depending on the variable(s) of interest.&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;for factor variables, it is more appropriate to compute frequencies and/or relative frequencies, and draw barplots&lt;/li&gt;
&lt;li&gt;for quantitative continuous variables, it is more appropriate to compute the mean, median, etc. and draw histograms, boxplots, etc.&lt;/li&gt;
&lt;li&gt;for logical variables, the mean,&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; a frequency table and a barplot are appropriate&lt;/li&gt;
&lt;li&gt;for character variables, &lt;a href=&#34;https://statsandr.com/blog/draw-a-word-cloud-with-a-shiny-app/&#34;&gt;word clouds&lt;/a&gt; are the most appropriate (unless the variable can be considered as a factor variable because there are not too many different levels)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We now illustrate the examples 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;pre class=&#34;r&#34;&gt;&lt;code&gt;## factor:
table(gender)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## gender
## female   male 
##      3      2&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;prop.table(table(gender))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## gender
## female   male 
##    0.6    0.4&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;barplot(table(gender))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/top-10-errors-in-r/index_files/figure-html/unnamed-chunk-34-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## quantitative continuous:
x &amp;lt;- rnorm(100)

summary(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
## -2.99309 -0.74143  0.01809 -0.08570  0.58937  2.70189&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;par(mfrow = c(1, 2)) ## combine two plots
hist(x)
boxplot(x)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/top-10-errors-in-r/index_files/figure-html/unnamed-chunk-34-2.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;## logical:
x &amp;lt;- c(TRUE, FALSE, FALSE, TRUE, TRUE)

mean(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.6&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;table(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## x
## FALSE  TRUE 
##     2     3&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;barplot(table(x))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/top-10-errors-in-r/index_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;For the interested reader, see the most common &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics in R&lt;/a&gt; for different types of data.&lt;/p&gt;
&lt;p&gt;Note that, as for descriptive statistics, the choice of the statistical test depends on the variable’s type. See this &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;flowchart&lt;/a&gt; to help you in selecting the most appropriate statistical test depending on the number of variables and their types.&lt;/p&gt;
&lt;p&gt;An error linked to the one mentioned above is &lt;strong&gt;inconsistent&lt;/strong&gt; data type. See it in practice with the following example:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x &amp;lt;- c(2.4, 3.7, 5.1, 9.8)
class(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;numeric&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;y &amp;lt;- c(2.4, 3.7, 5.1, &amp;quot;9.8&amp;quot;)
class(y)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;character&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, vector &lt;code&gt;x&lt;/code&gt; is numerical, whereas vector &lt;code&gt;y&lt;/code&gt; is in the form of character. This is due to the fact that the last element of &lt;code&gt;y&lt;/code&gt; is surrounded with quotation marks (and thus considered as a string instead of a numerical value), so the entire vector takes the character form.&lt;/p&gt;
&lt;p&gt;This can happen when you &lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/&#34;&gt;import a dataset into R&lt;/a&gt; and one or several elements of a variable are not encoded correctly. This leads to the entire variable to be considered as a character variable by R.&lt;/p&gt;
&lt;p&gt;To avoid this, it is a good practice to check the structure of your dataset (with &lt;code&gt;str()&lt;/code&gt;) after importing it to make sure all your variables have the desired format. If not, you can either correct the values in the initial file or change the format in R (with &lt;code&gt;as.numeric()&lt;/code&gt;).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;forgetting-the-sign-in-ggplot2&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;6. Forgetting the + sign in ggplot2&lt;/h1&gt;
&lt;p&gt;If you just learned to use the &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;ggplot2 package&lt;/a&gt; for your visualizations (and I highly recommend it!), a common mistake is to forget the &lt;code&gt;+&lt;/code&gt; sign.&lt;/p&gt;
&lt;p&gt;You know that a visualization made with ggplot2 is constructed by adding several layers:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## load package:
library(ggplot2)

## first layer, the dataset:
ggplot(data = diamonds) +
  ## second layer, the aesthetics:
  aes(x = cut, y = price) +
  ## third layer, the type of plot:
  geom_boxplot() +
  ## add more layers:
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/top-10-errors-in-r/index_files/figure-html/unnamed-chunk-37-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;solution-5&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Solution&lt;/h3&gt;
&lt;p&gt;For all your graphics with ggplot2, do not forget to add a &lt;strong&gt;&lt;code&gt;+&lt;/code&gt; sign after each layer &lt;em&gt;except&lt;/em&gt; the last one&lt;/strong&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;misunderstanding-between-and&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;7. Misunderstanding between = and ==&lt;/h1&gt;
&lt;p&gt;Assignment in R can be done in three ways, from the most to the least common:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;code&gt;&amp;lt;-&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;=&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;assign()&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The second method, that is &lt;code&gt;=&lt;/code&gt;, should not be confused with &lt;code&gt;==&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Indeed, assigning an object (with any of the three above methods) is used to save something in R. For example, if we want to save the vector &lt;code&gt;(1, 3, 7)&lt;/code&gt; and rename that vector &lt;code&gt;x&lt;/code&gt;, we can write:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x &amp;lt;- c(1, 3, 7)

## or:
x = c(1, 3, 7)

## or:
assign(&amp;quot;x&amp;quot;, c(1, 3, 7))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When executing this piece of code, you will see that the vector &lt;code&gt;x&lt;/code&gt; of size 3 appears in the tab “Environment” (the top right panel if you use the default view of RStudio):&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;images/R-environment.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;From now on, we can use that vector simply by calling it by its name:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1 3 7&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By no means, you can assign an object with &lt;code&gt;==&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## NOT correct if we want to assign c(1, 3, 7) to x:
x == c(1, 3, 7)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So you are wondering, when would we need to use &lt;code&gt;==&lt;/code&gt;? Actually, it is used when you want to use an equal sign.&lt;/p&gt;
&lt;p&gt;I understand that it may be abstract and confusing at the moment, so let’s suppose the following two scenarios as examples (which are the two most common cases when we use &lt;code&gt;==&lt;/code&gt;):&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;we want to check whether an assigned object or variable respects some conditions, and&lt;/li&gt;
&lt;li&gt;we want to subset a dataframe based on one or several conditions.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;For these examples, suppose a &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;sample&lt;/a&gt; of 5 children:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## create dataframe:
dat &amp;lt;- data.frame(
  Name = c(&amp;quot;Mary&amp;quot;, &amp;quot;Linda&amp;quot;, &amp;quot;James&amp;quot;, &amp;quot;John&amp;quot;, &amp;quot;Patricia&amp;quot;),
  Age = c(7, 10, 3, 9, 7),
  Gender = c(&amp;quot;Girl&amp;quot;, &amp;quot;Girl&amp;quot;, &amp;quot;Boy&amp;quot;, &amp;quot;Boy&amp;quot;, &amp;quot;Girl&amp;quot;)
)

## print dataframe:
dat&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       Name Age Gender
## 1     Mary   7   Girl
## 2    Linda  10   Girl
## 3    James   3    Boy
## 4     John   9    Boy
## 5 Patricia   7   Girl&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let’s now write different pieces of code for these two scenarios to illustrate them:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;We want to check whether the variable &lt;code&gt;Age&lt;/code&gt; is equal to the vector &lt;code&gt;(1, 2, 3, 4, 5)&lt;/code&gt;:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat$Age == 1:5&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] FALSE FALSE  TRUE FALSE FALSE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With this code, we ask whether the first element of the variable &lt;code&gt;Age&lt;/code&gt; is equal to 1, the second element of the variable &lt;code&gt;Age&lt;/code&gt; is equal to 2, and so on. The answer is of course &lt;code&gt;FALSE&lt;/code&gt;, &lt;code&gt;FALSE&lt;/code&gt;, &lt;code&gt;TRUE&lt;/code&gt;, &lt;code&gt;FALSE&lt;/code&gt; and &lt;code&gt;FALSE&lt;/code&gt; since only the third child has an age &lt;strong&gt;equal&lt;/strong&gt; to 3 years.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;We want to know which of our 5 sampled children are girls:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat$Gender == &amp;quot;Girl&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  TRUE  TRUE FALSE FALSE  TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The results show that the first, second and fifth children are girls, while the third and fourth children are not girls.&lt;/p&gt;
&lt;p&gt;If you write any of these two lines:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## this overwrites Age and Gender:
dat$Age = 1:5
dat$Gender = &amp;quot;Girl&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You actually overwrite the &lt;code&gt;Age&lt;/code&gt; and &lt;code&gt;Gender&lt;/code&gt; variables, such that our 5 children will have an age from 1 to 5 (1 year for the first child, up to 5 years for the fifth child) and all of them will be girls.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Now suppose we want to subset our dataframe based on a condition, namely, we want to extract only the children who are 7 years old:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;subset(dat, Age == 7)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       Name Age Gender
## 1     Mary   7   Girl
## 5 Patricia   7   Girl&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you do not want to use the subset function, you can also use square brackets:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat[dat$Age == 7, ]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       Name Age Gender
## 1     Mary   7   Girl
## 5 Patricia   7   Girl&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see in the previous examples, we do not want to assign anything. Instead, we are asking “is this variable or vector &lt;em&gt;equal&lt;/em&gt; to something else?”. For that specific need, we use &lt;code&gt;==&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;So to sum up, for technical reasons and in order to distinguish between the two concepts, R uses &lt;code&gt;=&lt;/code&gt; for assignments, and &lt;code&gt;==&lt;/code&gt; for the equality sign. Make sure to understand the difference between the two to avoid any errors.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;undefined-columns-selected&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;8. Undefined columns selected&lt;/h1&gt;
&lt;p&gt;If you are used to subset dataframes with square brackets, &lt;code&gt;[]&lt;/code&gt;, instead of the &lt;code&gt;subset()&lt;/code&gt; or &lt;code&gt;filter()&lt;/code&gt; functions, you may have faced the error “Error in [.data.frame(…) : undefined columns selected”.&lt;/p&gt;
&lt;p&gt;This occurs when R does not understand the column you want to use while subsetting the dataset.&lt;/p&gt;
&lt;p&gt;Considering the same sample of 5 children introduced earlier, the following code will throw an error:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat[dat$Age == 7]&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Error in `[.data.frame`(dat, dat$Age == 7) : undefined columns selected&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;because it does not specify the column dimension.&lt;/p&gt;
&lt;div id=&#34;solution-6&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Solution&lt;/h3&gt;
&lt;p&gt;Remember that dataframes in R have two dimensions:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;the rows (one for each experimental unit), and&lt;/li&gt;
&lt;li&gt;the columns (one for each variable)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;and &lt;strong&gt;in that particular order&lt;/strong&gt; (so row first, then column)!&lt;/p&gt;
&lt;p&gt;Since dataframes have two dimensions, R expects two dimensions when you call &lt;code&gt;dat[]&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;In particular, it expects the first and then the second dimension, &lt;strong&gt;separated by a comma&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat[dat$Age == 7, ]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       Name Age Gender
## 1     Mary   7   Girl
## 5 Patricia   7   Girl&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This code means that we are extracting all rows where &lt;code&gt;Age&lt;/code&gt; is equal to 7 (first dimension, i.e. before the comma), for all variables of the dataset (since we did not specify any column after the comma).&lt;/p&gt;
&lt;p&gt;For the interested reader, see more ways to &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/&#34;&gt;subset and manipulate data in R&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;problem-when-importing-or-using-the-wrong-data-file&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;9. Problem when importing or using the wrong data file&lt;/h1&gt;
&lt;p&gt;Importing a dataset in R can be quite challenging for beginners, mainly due to the misunderstanding about the working directory.&lt;/p&gt;
&lt;p&gt;When importing a file, &lt;strong&gt;R will not search for the file in all your folders&lt;/strong&gt; of your computer. Instead, it will look only in one specific folder. If your dataset is not inside that folder, it will result in an error such as “cannot open file ‘…’: No such file or directory”:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;images/cannot-open-file-no-such-file-or-directory.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;To fix this, you must specify the path to the folder where your dataset is located. In other words, you need to tell R in which folder you want it to work, hence the name working directory.&lt;/p&gt;
&lt;p&gt;Setting the working directory can be done with the &lt;code&gt;setwd()&lt;/code&gt; function or via the “Files” tab in the lower right panel of RStudio:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;images/files-r-studio.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Alternatively, you can move the dataset in the folder where R is currently working (this can be found with &lt;code&gt;getwd()&lt;/code&gt;). See more details on &lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/&#34;&gt;importing a file into R and about the working directory&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Another related problem is to use the wrong file. This error is different than the previous ones in the sense that you will not encounter an error but your analyses will still be wrong.&lt;/p&gt;
&lt;p&gt;It may sound trivial, but make sure to import and use the correct data file! This is particularly the case if you have files for different points in time and which have a common structure (for example weekly or monthly data files with the exact same variables). It happened to me that I reported results for the wrong week (fortunately, without much consequence).&lt;/p&gt;
&lt;p&gt;Also, make sure that you actually use all the rows you want to include in your analyses. It happened to me that, in order to test a model (and avoid long computing times), I extracted a random sample of the original dataset, and almost forgot about this sampling when running my final analyses.&lt;/p&gt;
&lt;p&gt;It is thus a good practice to remind you to remove sampling and filters after you have tested your code (and before interpreting the final results).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;problem-when-using-the-operator&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;10. Problem when using the $ operator&lt;/h1&gt;
&lt;p&gt;For the last error of this top 10, I would like to focus on two related errors:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;“$ operator is invalid for atomic vectors”, and&lt;/li&gt;
&lt;li&gt;“object of type ‘closure’ is not subsettable”.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;I gather them in one single section because they are linked to each other in the sense that they both involve the &lt;code&gt;$&lt;/code&gt; operator.&lt;/p&gt;
&lt;div id=&#34;operator-is-invalid-for-atomic-vectors&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;$ operator is invalid for atomic vectors&lt;/h2&gt;
&lt;p&gt;To understand this error, we first must recall that an atomic vector is a &lt;em&gt;one&lt;/em&gt;-dimensional object (usually created with &lt;code&gt;c()&lt;/code&gt;). This is different than dataframes or matrices which are &lt;em&gt;two&lt;/em&gt;-dimensional (i.e., rows form the first dimension and columns correspond to the second dimension).&lt;/p&gt;
&lt;p&gt;The error “$ operator is invalid for atomic vectors” occurs when we try to access an element of an atomic vector using the dollar operator (&lt;code&gt;$&lt;/code&gt;):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## define atomic vector:
x &amp;lt;- c(1, 3, 7)

## set names:
names(x) &amp;lt;- LETTERS[1:3]

## print vector:
x&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## A B C 
## 1 3 7&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## access value of element C:
x$C&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Error in x$C : $ operator is invalid for atomic vectors&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;solution-7&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Solution&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;$&lt;/code&gt; operator cannot be used to extract elements in atomic vectors. Instead, we must use double brackets &lt;code&gt;[[]]&lt;/code&gt; notation:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x[[&amp;quot;C&amp;quot;]]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 7&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Remember that the &lt;code&gt;$&lt;/code&gt; operator can be used with dataframes, so we can also fix this error by first converting the atomic vector to a dataframe,&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; and then access an element by its name with the &lt;code&gt;$&lt;/code&gt; operator:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## convert atomic vector to dataframe:
x &amp;lt;- as.data.frame(t(x))

## print x:
x&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   A B C
## 1 1 3 7&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## access value of element C:
x$C&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 7&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;object-of-type-closure-is-not-subsettable&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;object of type ‘closure’ is not subsettable&lt;/h2&gt;
&lt;p&gt;Another error (which I must admit is quite obscure and confusing when learning R) is the following: “object of type ‘closure’ is not subsettable”.&lt;/p&gt;
&lt;p&gt;This error occurs when we try to subset or access some elements of a function. An example with the well-known &lt;code&gt;mean()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mean[1:3]&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Error in mean[1:3] : object of type &amp;#39;closure&amp;#39; is not subsettable&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In R, we can subset lists, vectors, matrices, dataframes, but not functions. So it throws an error because it is impossible to subset an object of type “closure”, and a function is of that type:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;typeof(mean)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;closure&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Most of the times, you will not encounter this error when using a basic function such as the &lt;code&gt;mean()&lt;/code&gt; function (because it is unlikely that your goal is really to subset a function…).&lt;/p&gt;
&lt;p&gt;Indeed, you will most likely face this error when trying to subset a dataset named &lt;code&gt;data&lt;/code&gt;, but this dataset is not defined in the environment (because it has not been imported or created properly for instance).&lt;/p&gt;
&lt;p&gt;To understand the concept, see the following examples:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## create dataset:
data &amp;lt;- data.frame(
  x = rnorm(10),
  y = rnorm(10)
)

## print variable x:
data$x&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1]  1.12288964  1.43985574 -1.09711377 -0.11731956  1.20149840 -0.46972958
##  [7] -0.05246948 -0.08610730 -0.88767902 -0.44468400&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So far so good. Now suppose we made a mistake when creating the dataset:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## create dataset (with mistake):
data &amp;lt;- data.frame(x = rnorm(10)
                   y = rnorm(10))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You will notice that a comma is missing between variables &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt;. As a result, the dataset named &lt;code&gt;data&lt;/code&gt; is not created and thus not defined.&lt;/p&gt;
&lt;p&gt;Therefore, if we now try to access the variable &lt;code&gt;x&lt;/code&gt; from that dataset &lt;code&gt;data&lt;/code&gt;, R will actually try to subset the function named &lt;code&gt;data&lt;/code&gt; instead of the dataset named &lt;code&gt;data&lt;/code&gt;!&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;data$x&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;## Error in data$x : object of type &amp;#39;closure&amp;#39; is not subsettable&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This happens because, I repeat, the dataset &lt;code&gt;data&lt;/code&gt; does not exist, so R looks for an object named &lt;code&gt;data&lt;/code&gt; and find a function with that name:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;class(data)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;function&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;warnings&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Warnings&lt;/h1&gt;
&lt;p&gt;Warnings are different than errors in the sense that they alert you about something, but it does not prevent you from running the code. It is a good practice to read these warnings as they may give you valuable information.&lt;/p&gt;
&lt;p&gt;There are too many warnings to mention them all, but I would like to focus on two common ones:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;“NAs introduced by coercion”, and&lt;/li&gt;
&lt;li&gt;“Removed … rows containing non-finite values (stat_bin())”.&lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&#34;nas-introduced-by-coercion&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;NAs introduced by coercion&lt;/h2&gt;
&lt;p&gt;This warning occurs when you try to convert a vector which includes at least one non-numerical value to a numeric vector:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x &amp;lt;- c(1, 3, 7, &amp;quot;Emma&amp;quot;)

as.numeric(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Warning: NAs introduced by coercion&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  1  3  7 NA&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You do not need to fix it since it is only a warning and not an error. R is simply informing you that at least one element in the initial vector was converted to &lt;code&gt;NA&lt;/code&gt; because it could not be converted to a numeric value.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;removed-rows-containing-non-finite-values-stat_bin&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Removed … rows containing non-finite values (stat_bin())&lt;/h2&gt;
&lt;p&gt;This warning occurs when you use &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;ggplot2&lt;/a&gt; to draw plots. For instance:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(airquality) +
  aes(x = Ozone) +
  geom_histogram()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Warning: Removed 37 rows containing non-finite values (`stat_bin()`).&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/top-10-errors-in-r/index_files/figure-html/unnamed-chunk-65-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Again, as it is a warning you do not need to fix it. It is simply informing you that there are some missing values (&lt;code&gt;NA&lt;/code&gt;) in the variable of interest and that these missing values are removed to construct the plot.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope that this collection of errors prevented you from making some coding mistakes, or that it helped you in debugging your code.&lt;/p&gt;
&lt;p&gt;If you still cannot fix your error, I would recommend to read the documentation of the function (if you struggle with a function in particular), or look online for the solution. Bear in mind that if you encounter an error, it is very likely that someone else posted the answer online (Stack Overflow is usually a good resource).&lt;/p&gt;
&lt;p&gt;R has a steep learning curve, in particular if you are not familiar with another programming language. Nonetheless, with practice and time, you will make less and less coding errors, but more importantly, you will be more and more proficient in typing the right keywords in search engines, resulting in less time spent looking for the solution.&lt;/p&gt;
&lt;p&gt;As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;There are 2 mistakes in that piece of code, feel free to try to fix them as an exercise.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;And I strongly recommend using RStudio and not just R. See the differences &lt;a href=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio/&#34;&gt;here&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;Note that &lt;code&gt;mean()&lt;/code&gt; applied to a logical variable gives the proportion of &lt;code&gt;TRUE&lt;/code&gt;.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;&lt;code&gt;par(mfrow = c(1, 2))&lt;/code&gt; is used to put two plots next to 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;Note that we also need to take the transpose of the vector &lt;code&gt;x&lt;/code&gt; in order to have it as 1 row, 3 columns.&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>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>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>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>How to upload your R code on GitHub? An example with an R script on MacOS</title>
      <link>https://statsandr.com/blog/how-to-upload-r-code-on-github-example-with-an-r-script-on-mac-os/</link>
      <pubDate>Sun, 24 May 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/how-to-upload-r-code-on-github-example-with-an-r-script-on-mac-os/</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;#prerequisite&#34; id=&#34;toc-prerequisite&#34;&gt;Prerequisite&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#step-by-step-guide&#34; id=&#34;toc-step-by-step-guide&#34;&gt;Step-by-step guide&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#additional-notes&#34; id=&#34;toc-additional-notes&#34;&gt;Additional notes&lt;/a&gt;&lt;/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;A few days ago, a colleague asked me how to upload some R code on GitHub in order to make it accessible to everyone. Due to the lockdown, I could not just go into his office and show him on his computer. So I sent him several screenshots showing, step by step, how to do so.&lt;/p&gt;
&lt;p&gt;Right before I deleted the screenshots I’d just taken, I thought that perhaps they would be useful for other persons, so I wrote this article.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note 1: The screenshots have been taken on MacOS and I have not tested it on Windows. Do not hesitate to let me know in the comments whether it is similar or not on other operating systems.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note 2: There must be other ways to do it, but the method shown below is (in my opinion) easy and works well.&lt;/em&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;prerequisite&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Prerequisite&lt;/h1&gt;
&lt;p&gt;In order to follow this guide and upload your R code on GitHub, you will need at least:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a &lt;a href=&#34;https://github.com/&#34; target=&#34;_blank&#34;&gt;GitHub&lt;/a&gt; account&lt;/li&gt;
&lt;li&gt;the &lt;a href=&#34;https://desktop.github.com/&#34; target=&#34;_blank&#34;&gt;GitHub Desktop&lt;/a&gt; application installed on your computer&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;step-by-step-guide&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Step-by-step guide&lt;/h1&gt;
&lt;p&gt;For this guide, I use a R script created to plot the &lt;a href=&#34;https://statsandr.com/blog/covid-19-in-belgium-is-it-over-yet/&#34;&gt;evolution of the hospital admissions due to COVID-19 in Belgium&lt;/a&gt;. See the &lt;a href=&#34;https://github.com/AntoineSoetewey/COVID-19-Figures&#34; target=&#34;_blank&#34;&gt;repository on GitHub&lt;/a&gt; in case you want to see the final result before proceeding further.&lt;/p&gt;
&lt;p&gt;You often hear&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“A picture is worth a thousand words”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;So here is without further ado how to upload your R script on GitHub in images:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-1.png&#34; alt=&#34;Step 1: Go to github.com/login and sign in&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 1: Go to github.com/login and sign in&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-2.png&#34; alt=&#34;Step 2: Go to your GitHub profile and create a new repository&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 2: Go to your GitHub profile and create a new repository&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-3.png&#34; alt=&#34;Step 3: Set the name, description, audience and README file for the new repository&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 3: Set the name, description, audience and README file for the new repository&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;Be careful that if you choose to make it &lt;strong&gt;public&lt;/strong&gt;, it will be &lt;strong&gt;visible to everyone&lt;/strong&gt;. If you do not want to share the code, but still want it to be uploaded on GitHub, choose the private option.&lt;/p&gt;
&lt;p&gt;Initializing the repo with a README file is not mandatory, but I strongly recommend it so you will be able to add information for this repo.&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-4.png&#34; alt=&#34;Step 4: You now see your new repository with only the README file&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 4: You now see your new repository with only the README file&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-5.png&#34; alt=&#34;Step 5: Open the GitHub Desktop application and sign in with your GitHub account&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 5: Open the GitHub Desktop application and sign in with your GitHub account&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-6.png&#34; alt=&#34;Step 6 a: Clone the repository you just created on github.com to your computer&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 6 a: Clone the repository you just created on github.com to your computer&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-7.png&#34; alt=&#34;Step 6 b: Clone the repository you just created on github.com to your computer&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 6 b: Clone the repository you just created on github.com to your computer&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-8.png&#34; alt=&#34;Step 6 c: Clone the repository you just created on github.com to your computer&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 6 c: Clone the repository you just created on github.com to your computer&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-9.png&#34; alt=&#34;Step 7: Your new repo appears on the GitHub Desktop application&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 7: Your new repo appears on the GitHub Desktop application&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-10.png&#34; alt=&#34;Step 8: Open an R script and write your code&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 8: Open an R script and write your code&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;(See &lt;a href=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio/&#34;&gt;how to install R and RStudio&lt;/a&gt; if you are unfamiliar with it.)&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-11.png&#34; alt=&#34;Step 9 a: Save your R script in the corresponding folder&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 9 a: Save your R script in the corresponding folder&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;You can see the path to the folder in step 6 c, under “Local Path”.&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-12.png&#34; alt=&#34;Step 9 b: Save your R script in the corresponding folder&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 9 b: Save your R script in the corresponding folder&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-13.png&#34; alt=&#34;Step 10: Reopen GitHub Desktop, edit the commit title (1) and click on the commit button (2)&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 10: Reopen GitHub Desktop, edit the commit title (1) and click on the commit button (2)&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;In step 10, make sure that the current repository (see top left) is the repo you are currently working on.&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-14.png&#34; alt=&#34;Step 11: Push the commit to github.com&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 11: Push the commit to github.com&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-15.png&#34; alt=&#34;Step 12: On your GitHub profile, click on the newly created repository&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 12: On your GitHub profile, click on the newly created repository&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-16.png&#34; alt=&#34;Step 13: You now see your script which has been added to the repository&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 13: You now see your script which has been added to the repository&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;Your R code is now available online via the new repository on your GitHub profile. If you need to share it, you can simply share the URL of the repo.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;additional-notes&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Additional notes&lt;/h1&gt;
&lt;p&gt;If you need to edit your code:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Find the folder of the repo on your computer by clicking on the button “Show in Finder”:&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/find%20the%20repo%20on%20your%20computer.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Find the folder of your repo on your computer&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Find the folder of your repo on your computer&lt;/div&gt;
&lt;/div&gt;
&lt;ol start=&#34;2&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;You will be redirected to the folder of your repo on your computer. Open the R script you want to work on, edit it and save it:&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-17.png&#34; alt=&#34;Open the R script, edit it and save it&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Open the R script, edit it and save it&lt;/div&gt;
&lt;/div&gt;
&lt;ol start=&#34;3&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;After your script is saved, &lt;strong&gt;do not forget to commit the changes and push the commit&lt;/strong&gt; (see step 10 above).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In case you need to see an old version of your code, you can see all commits by clicking on the commits tab accessible via the repo on github.com:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-05-24-how-to-create-a-github-repository-for-r-scripts-on-macos_files/upload-r-code-on-GitHub-example-with-an-r-script-on-mac-os-18.png&#34; alt=&#34;See all commits&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;See all commits&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 create a GitHub repository, and upload your R scripts so that it is available to anyone.&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>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 create a simple Coronavirus dashboard specific to your country in R?</title>
      <link>https://statsandr.com/blog/how-to-create-a-simple-coronavirus-dashboard-specific-to-your-country-in-r/</link>
      <pubDate>Mon, 23 Mar 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/how-to-create-a-simple-coronavirus-dashboard-specific-to-your-country-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;#top-r-resources-on-coronavirus&#34; id=&#34;toc-top-r-resources-on-coronavirus&#34;&gt;Top R resources on Coronavirus&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#coronavirus-dashboard-the-case-of-belgium&#34; id=&#34;toc-coronavirus-dashboard-the-case-of-belgium&#34;&gt;Coronavirus dashboard: the case of Belgium&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#how-to-create-your-own-coronavirus-dashboard&#34; id=&#34;toc-how-to-create-your-own-coronavirus-dashboard&#34;&gt;How to create your own Coronavirus dashboard&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#additional-notes&#34; id=&#34;toc-additional-notes&#34;&gt;Additional notes&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#data&#34; id=&#34;toc-data&#34;&gt;Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#open-source&#34; id=&#34;toc-open-source&#34;&gt;Open source&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#accuracy&#34; id=&#34;toc-accuracy&#34;&gt;Accuracy&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#publish-your-dashboard&#34; id=&#34;toc-publish-your-dashboard&#34;&gt;Publish your dashboard&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/2020-03-23-how-to-create-a-simple-coronavirus-dashboard-specific-to-your-country-in-r_files/How%20to%20create%20a%20simple%20Coronavirus%20dashboard%20specific%20to%20your%20country%20in%20R-1.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Coronavirus dashboard: the case of Belgium&lt;/p&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;The Novel COVID-19 Coronavirus is the hottest topic right now. Every day, the media and newspapers share the number of new cases and deaths in several countries, try to measure the impacts of the virus on citizens and remind us to stay home in order to stay safe. The Coronavirus is on everyone’s lips.&lt;/p&gt;
&lt;p&gt;In addition to governments, media and companies discussing about it, data scientists and data professionals in general are putting their knowledge and time at the service of the virus. This leads to a proliferation of applications, dashboards, blog posts, videos, datasets and code analyzing, in one way or another, the expansion of the COVID-19 and how it spreads in the population.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;top-r-resources-on-coronavirus&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Top R resources on Coronavirus&lt;/h1&gt;
&lt;p&gt;As a data lover myself, I discovered a multitude of great resources about the Coronavirus. However, these resources were spread all over the internet and were often hidden by the mass of information of another type (e.g., alarming headlines, names of infected celebrities, companies showing off how they helped health care agencies, etc.). To tackle this issue, I collected and then shared in a previous article &lt;a href=&#34;https://statsandr.com/blog/top-r-resources-on-covid-19-coronavirus/&#34;&gt;the best R resources on the Coronavirus&lt;/a&gt; I came across.&lt;/p&gt;
&lt;p&gt;Note that only resources on R are shared in this article as R is my favorite statistical program and the one I am most familiar with. The fact that I use this program almost daily makes it easier for me to realize the complexity and time put behind a resource, and appreciate its quality and its potential.&lt;/p&gt;
&lt;p&gt;I am sure that there are other very interesting resources online (see for example the probably &lt;a href=&#34;https://coronavirus.jhu.edu/map.html&#34; target=&#34;_blank&#34;&gt;most popular dashboard&lt;/a&gt; by the Johns Hopkins Coronavirus Resource Center).&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; Nonetheless, a lot of people are in a better position than I am to judge the quality of resources made with programming languages for which I am not competent.&lt;/p&gt;
&lt;p&gt;This &lt;a href=&#34;https://statsandr.com/blog/top-r-resources-on-covid-19-coronavirus/&#34;&gt;article&lt;/a&gt; made me discover so many great resources about the Coronavirus and I keep receiving data visualizations and data analyses from scientists all over the world so that I include them in the collection. Thanks for that, it continuously improves the quality and completeness of the collection.&lt;/p&gt;
&lt;p&gt;In addition to receiving R resources, a question often asked by readers was “How can I create a dashboard myself?” or “How can I build a dashboard specific to my country?”. I therefore thought it would serve some people if I created a dashboard specific to my country (Belgium) and detailed the steps on how to build it.&lt;/p&gt;
&lt;p&gt;Questions on how to develop such dashboards came mostly from R beginners as advanced R users most probably know how to do one, or at least can easily use the resources I collected &lt;a href=&#34;https://statsandr.com/blog/top-r-resources-on-covid-19-coronavirus/&#34;&gt;here&lt;/a&gt; as sources of inspiration for their own work. Furthermore, in response to the craze about the Coronavirus, interested users were quite in a hurry and wanted to have their own dashboard running as quickly as possible.&lt;/p&gt;
&lt;p&gt;These questions led me to the idea of creating a simple (yet powerful and visually appealing) &lt;strong&gt;dashboard&lt;/strong&gt;, as opposed to a &lt;a href=&#34;https://statsandr.com/tags/shiny/&#34;&gt;Shiny app&lt;/a&gt;. Shiny apps have the advantage that they are interactive in the sense that users can edit the outputs and the visualizations by simply changing some inputs in a user-friendly way, while dashboards are static and cannot be modified by the final user. On the other hand, the advantage of a dashboard over a Shiny app is that it is much easier to code, especially if you are already proficient in &lt;a href=&#34;https://statsandr.com/blog/getting-started-in-r-markdown/&#34;&gt;R Markdown&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;coronavirus-dashboard-the-case-of-belgium&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Coronavirus dashboard: the case of Belgium&lt;/h1&gt;
&lt;p&gt;Amongst all the visualizations I have seen so far, one is standing out by its simplicity and at the same time, by its completeness and by the quality of its visualizations. I thus decided to create a Coronavirus dashboard based on this already existing &lt;a href=&#34;https://ramikrispin.github.io/coronavirus_dashboard/&#34; target=&#34;_blank&#34;&gt;dashboard&lt;/a&gt; by Rami Krispin (which comes with a license that allows to be freely adapted and shared) and adapt it so that it is specific to Belgium. Note that I also removed some visualizations and tables from the initial dashboard to keep it really simple and straight to the point.&lt;/p&gt;
&lt;p&gt;Before reading further, here is my &lt;a href=&#34;https://www.antoinesoetewey.com/files/coronavirus-dashboard.html&#34; target=&#34;_blank&#34;&gt;Coronavirus dashboard&lt;/a&gt; adapted to Belgium and previews of the main sections below:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-23-how-to-create-a-simple-coronavirus-dashboard-specific-to-your-country-in-r_files/How%20to%20create%20a%20simple%20Coronavirus%20dashboard%20specific%20to%20your%20country%20in%20R-1.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-23-how-to-create-a-simple-coronavirus-dashboard-specific-to-your-country-in-r_files/How%20to%20create%20a%20simple%20Coronavirus%20dashboard%20specific%20to%20your%20country%20in%20R-2.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-23-how-to-create-a-simple-coronavirus-dashboard-specific-to-your-country-in-r_files/How%20to%20create%20a%20simple%20Coronavirus%20dashboard%20specific%20to%20your%20country%20in%20R-3.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The dashboard is segmented into several sections that can be selected at the top:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The summary section provides key measures about the Coronavirus (total cases, active cases and deaths) and a plot displaying the cumulative number of active cases and deaths from January 22, 2020 to the latest available date.&lt;/li&gt;
&lt;li&gt;The comparison section presents a comparison of the number of daily new cases (left panel) and the distribution of cases by type (right panel) with other European countries (you can also change these countries by replacing them in the code).&lt;/li&gt;
&lt;li&gt;The map section shows a world map of the confirmed cases and deaths. You can uncheck one or several types of cases (top right corner) and zoom in or out (top left corner) to adapt the map to your needs.&lt;/li&gt;
&lt;li&gt;The about section gives more information about the data, the dashboard in general and how often it is updated.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I believe this simple dashboard is easy enough to be adapted to any country (and by anyone from beginner to expert), and still communicate key measures about the virus throughout some visualizations.&lt;/p&gt;
&lt;p&gt;A little extra which is worth mentioning is the fact that all plots are generated with the &lt;code&gt;{plotly}&lt;/code&gt; package. This package allows to enhance plots by displaying additional relevant information when hovering over them (try by yourself!).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;how-to-create-your-own-coronavirus-dashboard&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How to create your own Coronavirus dashboard&lt;/h1&gt;
&lt;p&gt;If you want to build your own dashboard specific to a country, follow these steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Open the dashboard &lt;a href=&#34;https://www.antoinesoetewey.com/files/coronavirus-dashboard.html&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;See the entire code via the button “Source code” located in the top right corner of the dashboard, or see the code on &lt;a href=&#34;https://github.com/AntoineSoetewey/coronavirus_dashboard&#34; target=&#34;_blank&#34;&gt;GitHub&lt;/a&gt;. Copy that code.&lt;/li&gt;
&lt;li&gt;Open a new R Markdown file (&lt;code&gt;.Rmd&lt;/code&gt;), type any title and author (they will be replaced in the next step anyway), select HTML as the output format and click on OK:&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/2020-03-23-how-to-create-a-simple-coronavirus-dashboard-specific-to-your-country-in-r_files/Screenshot%202020-03-23%20at%2015.38.45.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;ol start=&#34;4&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Remove all the template code already present and paste the code you copied in step 1.&lt;/li&gt;
&lt;li&gt;Make sure that the required packages are installed:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;install.packages(c(&amp;quot;devtools&amp;quot;, &amp;quot;flexdashboard&amp;quot;, &amp;quot;leaflet&amp;quot;, &amp;quot;leafpop&amp;quot;))
devtools::install_github(&amp;quot;RamiKrispin/coronavirus&amp;quot;, force = TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If R asks you which package you would like to update, there should be no need to update them: type 3 for “None”.&lt;/p&gt;
&lt;ol start=&#34;6&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;In the code, replace &lt;code&gt;Belgium&lt;/code&gt; with your country. Here is the list of all available countries in the dataset:&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;em&gt;Canada&lt;/em&gt;, &lt;em&gt;United Kingdom&lt;/em&gt;, &lt;em&gt;China&lt;/em&gt;, &lt;em&gt;Netherlands&lt;/em&gt;, &lt;em&gt;Australia&lt;/em&gt;, &lt;em&gt;New Zealand&lt;/em&gt;, &lt;em&gt;Denmark&lt;/em&gt;, &lt;em&gt;France&lt;/em&gt;, &lt;em&gt;Afghanistan&lt;/em&gt;, &lt;em&gt;Albania&lt;/em&gt;, &lt;em&gt;Algeria&lt;/em&gt;, &lt;em&gt;Andorra&lt;/em&gt;, &lt;em&gt;Angola&lt;/em&gt;, &lt;em&gt;Antarctica&lt;/em&gt;, &lt;em&gt;Antigua and Barbuda&lt;/em&gt;, &lt;em&gt;Argentina&lt;/em&gt;, &lt;em&gt;Armenia&lt;/em&gt;, &lt;em&gt;Austria&lt;/em&gt;, &lt;em&gt;Azerbaijan&lt;/em&gt;, &lt;em&gt;Bahamas&lt;/em&gt;, &lt;em&gt;Bahrain&lt;/em&gt;, &lt;em&gt;Bangladesh&lt;/em&gt;, &lt;em&gt;Barbados&lt;/em&gt;, &lt;em&gt;Belarus&lt;/em&gt;, &lt;em&gt;Belgium&lt;/em&gt;, &lt;em&gt;Belize&lt;/em&gt;, &lt;em&gt;Benin&lt;/em&gt;, &lt;em&gt;Bhutan&lt;/em&gt;, &lt;em&gt;Bolivia&lt;/em&gt;, &lt;em&gt;Bosnia and Herzegovina&lt;/em&gt;, &lt;em&gt;Botswana&lt;/em&gt;, &lt;em&gt;Brazil&lt;/em&gt;, &lt;em&gt;Brunei&lt;/em&gt;, &lt;em&gt;Bulgaria&lt;/em&gt;, &lt;em&gt;Burkina Faso&lt;/em&gt;, &lt;em&gt;Burma&lt;/em&gt;, &lt;em&gt;Burundi&lt;/em&gt;, &lt;em&gt;Cabo Verde&lt;/em&gt;, &lt;em&gt;Cambodia&lt;/em&gt;, &lt;em&gt;Cameroon&lt;/em&gt;, &lt;em&gt;Central African Republic&lt;/em&gt;, &lt;em&gt;Chad&lt;/em&gt;, &lt;em&gt;Chile&lt;/em&gt;, &lt;em&gt;Colombia&lt;/em&gt;, &lt;em&gt;Comoros&lt;/em&gt;, &lt;em&gt;Congo (Brazzaville)&lt;/em&gt;, &lt;em&gt;Congo (Kinshasa)&lt;/em&gt;, &lt;em&gt;Costa Rica&lt;/em&gt;, &lt;em&gt;Cote d’Ivoire&lt;/em&gt;, &lt;em&gt;Croatia&lt;/em&gt;, &lt;em&gt;Cuba&lt;/em&gt;, &lt;em&gt;Cyprus&lt;/em&gt;, &lt;em&gt;Czechia&lt;/em&gt;, &lt;em&gt;Diamond Princess&lt;/em&gt;, &lt;em&gt;Djibouti&lt;/em&gt;, &lt;em&gt;Dominica&lt;/em&gt;, &lt;em&gt;Dominican Republic&lt;/em&gt;, &lt;em&gt;Ecuador&lt;/em&gt;, &lt;em&gt;Egypt&lt;/em&gt;, &lt;em&gt;El Salvador&lt;/em&gt;, &lt;em&gt;Equatorial Guinea&lt;/em&gt;, &lt;em&gt;Eritrea&lt;/em&gt;, &lt;em&gt;Estonia&lt;/em&gt;, &lt;em&gt;Eswatini&lt;/em&gt;, &lt;em&gt;Ethiopia&lt;/em&gt;, &lt;em&gt;Fiji&lt;/em&gt;, &lt;em&gt;Finland&lt;/em&gt;, &lt;em&gt;Gabon&lt;/em&gt;, &lt;em&gt;Gambia&lt;/em&gt;, &lt;em&gt;Georgia&lt;/em&gt;, &lt;em&gt;Germany&lt;/em&gt;, &lt;em&gt;Ghana&lt;/em&gt;, &lt;em&gt;Greece&lt;/em&gt;, &lt;em&gt;Grenada&lt;/em&gt;, &lt;em&gt;Guatemala&lt;/em&gt;, &lt;em&gt;Guinea&lt;/em&gt;, &lt;em&gt;Guinea-Bissau&lt;/em&gt;, &lt;em&gt;Guyana&lt;/em&gt;, &lt;em&gt;Haiti&lt;/em&gt;, &lt;em&gt;Holy See&lt;/em&gt;, &lt;em&gt;Honduras&lt;/em&gt;, &lt;em&gt;Hungary&lt;/em&gt;, &lt;em&gt;Iceland&lt;/em&gt;, &lt;em&gt;India&lt;/em&gt;, &lt;em&gt;Indonesia&lt;/em&gt;, &lt;em&gt;Iran&lt;/em&gt;, &lt;em&gt;Iraq&lt;/em&gt;, &lt;em&gt;Ireland&lt;/em&gt;, &lt;em&gt;Israel&lt;/em&gt;, &lt;em&gt;Italy&lt;/em&gt;, &lt;em&gt;Jamaica&lt;/em&gt;, &lt;em&gt;Japan&lt;/em&gt;, &lt;em&gt;Jordan&lt;/em&gt;, &lt;em&gt;Kazakhstan&lt;/em&gt;, &lt;em&gt;Kenya&lt;/em&gt;, &lt;em&gt;Kiribati&lt;/em&gt;, &lt;em&gt;Korea, North&lt;/em&gt;, &lt;em&gt;Korea, South&lt;/em&gt;, &lt;em&gt;Kosovo&lt;/em&gt;, &lt;em&gt;Kuwait&lt;/em&gt;, &lt;em&gt;Kyrgyzstan&lt;/em&gt;, &lt;em&gt;Laos&lt;/em&gt;, &lt;em&gt;Latvia&lt;/em&gt;, &lt;em&gt;Lebanon&lt;/em&gt;, &lt;em&gt;Lesotho&lt;/em&gt;, &lt;em&gt;Liberia&lt;/em&gt;, &lt;em&gt;Libya&lt;/em&gt;, &lt;em&gt;Liechtenstein&lt;/em&gt;, &lt;em&gt;Lithuania&lt;/em&gt;, &lt;em&gt;Luxembourg&lt;/em&gt;, &lt;em&gt;Madagascar&lt;/em&gt;, &lt;em&gt;Malawi&lt;/em&gt;, &lt;em&gt;Malaysia&lt;/em&gt;, &lt;em&gt;Maldives&lt;/em&gt;, &lt;em&gt;Mali&lt;/em&gt;, &lt;em&gt;Malta&lt;/em&gt;, &lt;em&gt;Marshall Islands&lt;/em&gt;, &lt;em&gt;Mauritania&lt;/em&gt;, &lt;em&gt;Mauritius&lt;/em&gt;, &lt;em&gt;Mexico&lt;/em&gt;, &lt;em&gt;Micronesia&lt;/em&gt;, &lt;em&gt;Moldova&lt;/em&gt;, &lt;em&gt;Monaco&lt;/em&gt;, &lt;em&gt;Mongolia&lt;/em&gt;, &lt;em&gt;Montenegro&lt;/em&gt;, &lt;em&gt;Morocco&lt;/em&gt;, &lt;em&gt;Mozambique&lt;/em&gt;, &lt;em&gt;MS Zaandam&lt;/em&gt;, &lt;em&gt;Namibia&lt;/em&gt;, &lt;em&gt;Nepal&lt;/em&gt;, &lt;em&gt;Nicaragua&lt;/em&gt;, &lt;em&gt;Niger&lt;/em&gt;, &lt;em&gt;Nigeria&lt;/em&gt;, &lt;em&gt;North Macedonia&lt;/em&gt;, &lt;em&gt;Norway&lt;/em&gt;, &lt;em&gt;Oman&lt;/em&gt;, &lt;em&gt;Pakistan&lt;/em&gt;, &lt;em&gt;Palau&lt;/em&gt;, &lt;em&gt;Panama&lt;/em&gt;, &lt;em&gt;Papua New Guinea&lt;/em&gt;, &lt;em&gt;Paraguay&lt;/em&gt;, &lt;em&gt;Peru&lt;/em&gt;, &lt;em&gt;Philippines&lt;/em&gt;, &lt;em&gt;Poland&lt;/em&gt;, &lt;em&gt;Portugal&lt;/em&gt;, &lt;em&gt;Qatar&lt;/em&gt;, &lt;em&gt;Romania&lt;/em&gt;, &lt;em&gt;Russia&lt;/em&gt;, &lt;em&gt;Rwanda&lt;/em&gt;, &lt;em&gt;Saint Kitts and Nevis&lt;/em&gt;, &lt;em&gt;Saint Lucia&lt;/em&gt;, &lt;em&gt;Saint Vincent and the Grenadines&lt;/em&gt;, &lt;em&gt;Samoa&lt;/em&gt;, &lt;em&gt;San Marino&lt;/em&gt;, &lt;em&gt;Sao Tome and Principe&lt;/em&gt;, &lt;em&gt;Saudi Arabia&lt;/em&gt;, &lt;em&gt;Senegal&lt;/em&gt;, &lt;em&gt;Serbia&lt;/em&gt;, &lt;em&gt;Seychelles&lt;/em&gt;, &lt;em&gt;Sierra Leone&lt;/em&gt;, &lt;em&gt;Singapore&lt;/em&gt;, &lt;em&gt;Slovakia&lt;/em&gt;, &lt;em&gt;Slovenia&lt;/em&gt;, &lt;em&gt;Solomon Islands&lt;/em&gt;, &lt;em&gt;Somalia&lt;/em&gt;, &lt;em&gt;South Africa&lt;/em&gt;, &lt;em&gt;South Sudan&lt;/em&gt;, &lt;em&gt;Spain&lt;/em&gt;, &lt;em&gt;Sri Lanka&lt;/em&gt;, &lt;em&gt;Sudan&lt;/em&gt;, &lt;em&gt;Summer Olympics 2020&lt;/em&gt;, &lt;em&gt;Suriname&lt;/em&gt;, &lt;em&gt;Sweden&lt;/em&gt;, &lt;em&gt;Switzerland&lt;/em&gt;, &lt;em&gt;Syria&lt;/em&gt;, _Taiwan*_, &lt;em&gt;Tajikistan&lt;/em&gt;, &lt;em&gt;Tanzania&lt;/em&gt;, &lt;em&gt;Thailand&lt;/em&gt;, &lt;em&gt;Timor-Leste&lt;/em&gt;, &lt;em&gt;Togo&lt;/em&gt;, &lt;em&gt;Tonga&lt;/em&gt;, &lt;em&gt;Trinidad and Tobago&lt;/em&gt;, &lt;em&gt;Tunisia&lt;/em&gt;, &lt;em&gt;Turkey&lt;/em&gt;, &lt;em&gt;Uganda&lt;/em&gt;, &lt;em&gt;Ukraine&lt;/em&gt;, &lt;em&gt;United Arab Emirates&lt;/em&gt;, &lt;em&gt;Uruguay&lt;/em&gt;, &lt;em&gt;US&lt;/em&gt;, &lt;em&gt;Uzbekistan&lt;/em&gt;, &lt;em&gt;Vanuatu&lt;/em&gt;, &lt;em&gt;Venezuela&lt;/em&gt;, &lt;em&gt;Vietnam&lt;/em&gt;, &lt;em&gt;West Bank and Gaza&lt;/em&gt;, &lt;em&gt;Winter Olympics 2022&lt;/em&gt;, &lt;em&gt;Yemen&lt;/em&gt;, &lt;em&gt;Zambia&lt;/em&gt; and &lt;em&gt;Zimbabwe&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Note that if your country is spelled in two words or more, you will need to surround it by a backtick (but only at one specific line in the code, see an example with United Kingdom):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#----------------------------------------
# Plotting the data

daily_confirmed %&amp;gt;%
  plotly::plot_ly() %&amp;gt;%
  plotly::add_trace(
    x = ~date,
    y = ~`United Kingdom`,
    type = &amp;quot;scatter&amp;quot;,
    mode = &amp;quot;lines+markers&amp;quot;,
    name = &amp;quot;United Kingdom&amp;quot;
  ) %&amp;gt;%&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Do not add backticks in the rest of the code as everywhere else the country’s name is surrounded by double quotes &lt;code&gt;&#34;&#34;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Do not forget to also change the title and the author at the top of the document, and edit the about section at the bottom of the document. Last but not least, as you can see on the plot in the summary section, the arrows point to different (sad) “milestones” in Belgium (i.e., first case, first death and new containment measures).&lt;/p&gt;
&lt;p&gt;You will need to adapt these milestones for your country (or remove them if you do not want to have any milestone displayed on the plot). Change this in the code following the &lt;code&gt;plotly::add_annotations()&lt;/code&gt; functions.&lt;/p&gt;
&lt;ol start=&#34;7&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Knit the document (see this &lt;a href=&#34;https://statsandr.com/blog/getting-started-in-r-markdown/&#34;&gt;article&lt;/a&gt; if you are unfamiliar with R Markdown). Your dashboard should appear in HTML format.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Following these 7 steps, you should already have a simple dashboard specific to your country. I have intentionally kept it simple so that everyone could copy it and have their own dashboard in a limited amount of time.&lt;/p&gt;
&lt;p&gt;If you are familiar with the &lt;a href=&#34;https://rmarkdown.rstudio.com/flexdashboard/&#34; target=&#34;_blank&#34;&gt;&lt;code&gt;{flexdashboard}&lt;/code&gt;&lt;/a&gt;, &lt;a href=&#34;https://plot.ly/r/&#34; target=&#34;_blank&#34;&gt;&lt;code&gt;{plotly}&lt;/code&gt;&lt;/a&gt; and &lt;a href=&#34;https://rstudio.github.io/leaflet/&#34; target=&#34;_blank&#34;&gt;&lt;code&gt;{leaflet}&lt;/code&gt;&lt;/a&gt; packages for the dashboard interface and the visualizations, and the &lt;a href=&#34;https://dplyr.tidyverse.org/&#34; target=&#34;_blank&#34;&gt;&lt;code&gt;{dplyr}&lt;/code&gt;&lt;/a&gt; and &lt;a href=&#34;https://tidyr.tidyverse.org/&#34; target=&#34;_blank&#34;&gt;&lt;code&gt;{tidyr}&lt;/code&gt;&lt;/a&gt; packages for the data manipulation, feel free to edit the code according to your needs and improve your dashboard.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;additional-notes&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Additional notes&lt;/h1&gt;
&lt;div id=&#34;data&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Data&lt;/h2&gt;
&lt;p&gt;The input data for this dashboard is the dataset available from the &lt;a href=&#34;https://github.com/RamiKrispin/coronavirus&#34; target=&#34;_blank&#34;&gt;&lt;code&gt;{coronavirus}&lt;/code&gt;&lt;/a&gt; R package. Make sure to download the development version of the package to have the latest data:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;install.packages(&amp;quot;devtools&amp;quot;)
devtools::install_github(&amp;quot;RamiKrispin/coronavirus&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To update your dashboard with the latest data, you have to manually update the data by reinstalling the &lt;code&gt;{coronavirus}&lt;/code&gt; package with &lt;code&gt;devtools::install_github(&#34;RamiKrispin/coronavirus&#34;, force = TRUE)&lt;/code&gt;. Again, if R asks you whether you would like to update other packages, type 3 for “None”.&lt;/p&gt;
&lt;p&gt;This question was often raised so I repeat, your dashboard will not update by itself every day, you need to manually update it. After updating the data, you may also need to restart your R session in order to have the last available data.&lt;/p&gt;
&lt;p&gt;The raw data is pulled from the Johns Hopkins University Center for Systems Science and Engineering (JHU CCSE) Coronavirus &lt;a href=&#34;https://github.com/RamiKrispin/coronavirus-csv&#34; target=&#34;_blank&#34;&gt;repository&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;open-source&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Open source&lt;/h2&gt;
&lt;p&gt;This dashboard and the code available on &lt;a href=&#34;https://github.com/AntoineSoetewey/coronavirus_dashboard&#34; target=&#34;_blank&#34;&gt;GitHub&lt;/a&gt; are open source so feel free to copy it, adapt it and share it as much as you want.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;accuracy&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Accuracy&lt;/h2&gt;
&lt;p&gt;Please note that this dashboard has been built mainly for educational purposes. I update the dashboard as often as possible to keep it accurate. However, there is some uncertainty concerning the COVID-19 case numbers and the testing methods vary between countries so the figures on this dashboard may be slightly different compared to other sources. Currently, the maintainer of the &lt;a href=&#34;https://statsandr.com/blog/how-to-create-a-simple-coronavirus-dashboard-specific-to-your-country-in-r/#data&#34;&gt;dataset&lt;/a&gt; updates it on a daily basis, but updates may become less frequent in the future.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;publish-your-dashboard&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Publish your dashboard&lt;/h2&gt;
&lt;p&gt;If you want to share your dashboard, you can either:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Upload it on your website if you have one (and I strongly suggest you to &lt;a href=&#34;https://statsandr.com/blog/7-benefits-of-sharing-your-code-in-a-data-science-blog/#how-to-start-your-own-blog&#34;&gt;create one&lt;/a&gt; if you do not already have one)&lt;/li&gt;
&lt;li&gt;Publish it through &lt;a href=&#34;https://rpubs.com/&#34; target=&#34;_blank&#34;&gt;RPubs&lt;/a&gt; (it is free and easy to publish your work directly from RStudio)&lt;/li&gt;
&lt;/ul&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 build your first Coronavirus dashboard in R. See these &lt;a href=&#34;https://statsandr.com/blog/top-r-resources-on-covid-19-coronavirus/&#34;&gt;top R resources on Coronavirus&lt;/a&gt; if you need inspiration to enhance further your dashboard.&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;I would be glad to mention a collection of Python resources if someone is willing to create a collection of resources about the Coronavirus made with this programming language. Feel free to &lt;a href=&#34;https://statsandr.com/contact/&#34;&gt;contact me&lt;/a&gt; if this is the case.&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>How to perform a one-sample t-test by hand and in R: test on one mean</title>
      <link>https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r-test-on-one-mean/</link>
      <pubDate>Mon, 09 Mar 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r-test-on-one-mean/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#null-and-alternative-hypothesis&#34; id=&#34;toc-null-and-alternative-hypothesis&#34;&gt;Null and alternative hypothesis&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#hypothesis-testing&#34; id=&#34;toc-hypothesis-testing&#34;&gt;Hypothesis testing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#two-versions-of-the-one-sample-t-test&#34; id=&#34;toc-two-versions-of-the-one-sample-t-test&#34;&gt;Two versions of the one-sample t-test&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#how-to-compute-the-one-sample-t-test-by-hand&#34; id=&#34;toc-how-to-compute-the-one-sample-t-test-by-hand&#34;&gt;How to compute the one-sample t-test by hand?&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-1-variance-of-the-population-is-known&#34; id=&#34;toc-scenario-1-variance-of-the-population-is-known&#34;&gt;Scenario 1: variance of the population is known&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-2-variance-of-the-population-is-unknown&#34; id=&#34;toc-scenario-2-variance-of-the-population-is-unknown&#34;&gt;Scenario 2: variance of the population is unknown&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#different-underlying-distributions-for-the-critical-value&#34; id=&#34;toc-different-underlying-distributions-for-the-critical-value&#34;&gt;Different underlying distributions for the critical value&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#how-to-compute-the-one-sample-t-test-in-r&#34; id=&#34;toc-how-to-compute-the-one-sample-t-test-in-r&#34;&gt;How to compute the one-sample t-test in R?&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-1-variance-of-the-population-is-known-1&#34; id=&#34;toc-scenario-1-variance-of-the-population-is-known-1&#34;&gt;Scenario 1: variance of the population is known&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-2-variance-of-the-population-is-unknown-1&#34; id=&#34;toc-scenario-2-variance-of-the-population-is-unknown-1&#34;&gt;Scenario 2: variance of the population is unknown&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#confidence-interval&#34; id=&#34;toc-confidence-interval&#34;&gt;Confidence interval&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#combination-of-plot-and-statistical-test&#34; id=&#34;toc-combination-of-plot-and-statistical-test&#34;&gt;Combination of plot and statistical test&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#scenario-2-variance-of-the-population-is-unknown-2&#34; id=&#34;toc-scenario-2-variance-of-the-population-is-unknown-2&#34;&gt;Scenario 2: variance of the population is unknown&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#assumptions&#34; id=&#34;toc-assumptions&#34;&gt;Assumptions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r_files/how-to-perform-a-one-sample-t-test-by-hand-and-in-r.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;After having written an article on the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test for two samples&lt;/a&gt; (independent and paired samples), I believe it is time to explain in details how to perform one-sample t-tests by hand and in R.&lt;/p&gt;
&lt;p&gt;One-sample t-test is an important part of inferential statistics (probably one of the first &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical test&lt;/a&gt; that students learn). Remind that, unlike &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics&lt;/a&gt;, inferential statistics is a branch of statistics aiming at drawing conclusions about one or two &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;populations&lt;/a&gt;, based on a subset (or two) of that population (called samples). In other words, we first collect a random set of observations from a population, and then some measurements are calculated in order to generalize to the population the information found through the sample.&lt;/p&gt;
&lt;p&gt;In this context, the &lt;strong&gt;one-sample t-test is used to determine whether the mean of a measurement variable is different from a specified value&lt;/strong&gt; (a belief or a theoretical expectation for example). It works as follows: if the mean of the sample is too distant from the specified value (the value under the null hypothesis), it is considered that the mean of the population is different from what is expected. On the contrary, if the mean of the sample is close to the specified value, we cannot reject the hypothesis that the population mean is equal to what is expected.&lt;/p&gt;
&lt;p&gt;Like the &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student’s t-test for two samples&lt;/a&gt; and the &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;ANOVA&lt;/a&gt; (for 3 or more samples), there are also different versions of the one-sample t-test. Luckily, there are only two different versions for this test (the Student’s t-test for two samples has 5 versions!). The difference between the two versions of the one-sample t-test lies in the fact that one version is used when the variance of the &lt;em&gt;population&lt;/em&gt; (not the variance of the sample!) is known, the other version being used when the variance of the population is unknown.&lt;/p&gt;
&lt;p&gt;In this article, I will first detail step by step how to perform both versions of the one-sample t-test by hand. The analyses will be done on a small set of observations for the sake of illustration and easiness. I will then show how to perform this test in R with the exact same data in order to verify the results found by hand. Reminders about the reasoning behind &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt;, interpretations of the &lt;em&gt;p&lt;/em&gt;-value and the results, and assumptions of this test will also be presented.&lt;/p&gt;
&lt;p&gt;Note that the aim of this article is to show how to compute the one-sample t-test by hand and in R, so we refrain from testing the assumptions and we assume all assumptions are met for this exercise. For completeness, we still mention the assumptions and how to test them. Interested readers are invited to have a look at the &lt;a href=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r-test-on-one-mean/#assumptions&#34;&gt;end of the article&lt;/a&gt; for more information about these assumptions.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;null-and-alternative-hypothesis&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Null and alternative hypothesis&lt;/h1&gt;
&lt;p&gt;Before diving into the computations of the one-sample t-test by hand, let’s recap the null and alternative hypotheses of this test:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu = \mu_0\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu \ne \mu_0\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; is the population mean and &lt;span class=&#34;math inline&#34;&gt;\(\mu_0\)&lt;/span&gt; is the known or &lt;strong&gt;hypothesized&lt;/strong&gt; value of the mean in the population.&lt;/p&gt;
&lt;p&gt;This is in the general case where we simply want to determine whether the population mean is &lt;strong&gt;different&lt;/strong&gt; (in terms of the dependent variable) compared to the hypothesized value. In this sense, we have no prior belief about the population mean being larger or smaller than the hypothesized value. This type of test is referred as a &lt;strong&gt;two-sided&lt;/strong&gt; or bilateral test.&lt;/p&gt;
&lt;p&gt;If we have some prior beliefs about the population mean being larger or smaller than the hypothesized value, the one-sample t-test also allows to test the following hypotheses:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu = \mu_0\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu &amp;gt; \mu_0\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;or&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu = \mu_0\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: &lt;span class=&#34;math inline&#34;&gt;\(\mu &amp;lt; \mu_0\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In the first case, we want to test if the population mean is significantly larger than the hypothesized value, while in the latter case, we want to test if the population mean is significantly smaller than the hypothesized value. This type of test is referred as a &lt;strong&gt;one-sided&lt;/strong&gt; or unilateral test.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;hypothesis-testing&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Hypothesis testing&lt;/h1&gt;
&lt;p&gt;In statistics, many statistical tests is in the form of &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt;. Hypothesis tests are used to determine whether a certain belief can be deemed as true (plausible) or not, based on the data at hand (i.e., the sample(s)). Most hypothesis tests boil down to the following 4 steps:&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;State the null and alternative hypothesis.&lt;/li&gt;
&lt;li&gt;Compute the test statistic, denoted t-stat. Formulas to compute the test statistic differ among the different versions of the one-sample t-test but they have the same structure. See scenarios 1 and 2 below to see the different formulas.&lt;/li&gt;
&lt;li&gt;Find the critical value given the theoretical statistical distribution of the test, the parameters of the distribution and the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;. For the two versions of the one-sample t-test, it is either the normal or the Student’s t distribution (&lt;em&gt;t&lt;/em&gt; denoting the Student distribution and &lt;em&gt;z&lt;/em&gt; denoting the normal distribution).&lt;/li&gt;
&lt;li&gt;Conclude by comparing the t-stat (found in step 2.) with the critical value (found in step. 3). If the t-stat lies in the rejection region (determined thanks to the critical value and the direction of the test), we reject the null hypothesis, otherwise we do not reject the null hypothesis. These two alternatives (reject or do not reject the null hypothesis) are the only two possible solutions, we never “accept” an hypothesis. It is also a good practice to always interpret the decision in the terms of the initial question.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;For the interested reader, see these 4 steps of hypothesis testing in more details in this &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;article&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;two-versions-of-the-one-sample-t-test&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Two versions of the one-sample t-test&lt;/h1&gt;
&lt;p&gt;There are two versions of the one-sample t-test, depending on whether the variance of the population (not the variance of the sample!) is known or unknown. This criteria is rather straightforward, we either know the variance of the population or we do not. The variance of the population cannot be computed because if you can compute the variance of a population, it means you have the data for the whole population, then there is no need to do a hypothesis test anymore…&lt;/p&gt;
&lt;p&gt;So the variance of the population is either given in the statement (use them in that case), or there is no information about the variance and in that case, it is assumed that the variance is unknown. In practice, the variance of the population is most of the time unknown. However, we still illustrate how to do both versions of this test by hand and in R in the next sections following the 4 steps of a hypothesis test.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;how-to-compute-the-one-sample-t-test-by-hand&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How to compute the one-sample t-test by hand?&lt;/h1&gt;
&lt;p&gt;Note that the data are artificial and do not represent any real variable. Furthermore, remind that the assumptions may or may not be met. The point of the article is to detail how to compute the different versions of the test by hand and in R, so all assumptions are assumed to be met. Moreover, we assume that for all tests the significance level, that is, the type I error is &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 5\)&lt;/span&gt;%.&lt;/p&gt;
&lt;p&gt;If you are interested in applying these tests by hand without having to do the computations yourself, here is a &lt;a href=&#34;https://statsandr.com/blog/a-shiny-app-for-inferential-statistics-by-hand/&#34;&gt;Shiny app&lt;/a&gt; which does it for you. You just need to enter the data and choose the appropriate version of the test thanks to the sidebar menu. There is also a graphical representation that helps you to visualize the test statistic and the rejection region. I hope you will find it useful!&lt;/p&gt;
&lt;div id=&#34;scenario-1-variance-of-the-population-is-known&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 1: variance of the population is known&lt;/h2&gt;
&lt;p&gt;For the first scenario, suppose the data below. Moreover, suppose that the population variance &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2 = 1\)&lt;/span&gt; and that we would like to test whether the population mean is different from 0.&lt;/p&gt;
&lt;table style=&#34;width:11%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;11%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt;value&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;0.9&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;-0.8&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1.3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;-0.3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1.7&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;So we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;5 observations: &lt;span class=&#34;math inline&#34;&gt;\(n = 5\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;mean of the sample: &lt;span class=&#34;math inline&#34;&gt;\(\bar{x} = 0.56\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;variance of the population: &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2 = 1\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\mu_0 = 0\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Following the 4 steps of hypothesis testing we have:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu = 0\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu \ne 0\)&lt;/span&gt;. (&lt;span class=&#34;math inline&#34;&gt;\(\ne\)&lt;/span&gt; because we want to test whether the population mean is different from 0, we do not impose a direction in the test.)&lt;/li&gt;
&lt;li&gt;Test statistic: &lt;span class=&#34;math display&#34;&gt;\[z_{obs} = \frac{\bar{x} - \mu_0}{\frac{\sigma}{\sqrt{n}}} = \frac{0.56-0}{0.447} = 1.252\]&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Critical value: &lt;span class=&#34;math inline&#34;&gt;\(\pm z_{\alpha / 2} = \pm z_{0.025} = \pm 1.96\)&lt;/span&gt; (see a guide on &lt;a href=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/&#34;&gt;how to read statistical tables&lt;/a&gt; if you struggle to find the critical value)&lt;/li&gt;
&lt;li&gt;Conclusion: The rejection regions are thus from &lt;span class=&#34;math inline&#34;&gt;\(-\infty\)&lt;/span&gt; to -1.96 and from 1.96 to &lt;span class=&#34;math inline&#34;&gt;\(+\infty\)&lt;/span&gt;. The test statistic is outside the rejection regions so we do not reject the null hypothesis &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;. In terms of the initial question: At the 5% significance level, we do not reject the hypothesis that the population mean is equal to 0, or there is no sufficient evidence in the data to conclude that the population mean is different from 0.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div id=&#34;scenario-2-variance-of-the-population-is-unknown&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 2: variance of the population is unknown&lt;/h2&gt;
&lt;p&gt;For the second scenario, suppose the data below. Moreover, suppose that the variance in the population is unknown and that we would like to test whether the population mean is larger than 5.&lt;/p&gt;
&lt;table style=&#34;width:11%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;11%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt;value&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;7.9&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;5.8&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;6.3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;7.3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;6.7&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;So we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;5 observations: &lt;span class=&#34;math inline&#34;&gt;\(n = 5\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;mean of the sample: &lt;span class=&#34;math inline&#34;&gt;\(\bar{x} = 6.8\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;standard deviation of the sample: &lt;span class=&#34;math inline&#34;&gt;\(s = 0.825\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\mu_0 = 5\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Following the 4 steps of hypothesis testing we have:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0: \mu = 5\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu &amp;gt; 5\)&lt;/span&gt;. (&amp;gt; because we want to test whether the population mean is larger than 5.)&lt;/li&gt;
&lt;li&gt;Test statistic: &lt;span class=&#34;math display&#34;&gt;\[t_{obs} = \frac{\bar{x} - \mu_0}{\frac{s}{\sqrt{n}}} = \frac{6.8-5}{0.369} = 4.881\]&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Critical value: &lt;span class=&#34;math inline&#34;&gt;\(t_{\alpha, n - 1} = t_{0.05, 4} = 2.132\)&lt;/span&gt; (see a guide on &lt;a href=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/&#34;&gt;how to read statistical tables&lt;/a&gt; if you struggle to find the critical value)&lt;/li&gt;
&lt;li&gt;Conclusion: The rejection region is thus from 2.132 to &lt;span class=&#34;math inline&#34;&gt;\(+\infty\)&lt;/span&gt;. The test statistic lies within the rejection region so we reject the null hypothesis &lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;. In terms of the initial question: At the 5% significance level, we conclude that the population mean is larger than 5.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This concludes how to perform the two versions of the one-sample t-test by hand. In the next sections, we detail how to perform the exact same tests in R.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;different-underlying-distributions-for-the-critical-value&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Different underlying distributions for the critical value&lt;/h2&gt;
&lt;p&gt;As you may have noticed, the underlying probability distributions used to find the critical value are different depending on whether the variance of the population is known or unknown.&lt;/p&gt;
&lt;p&gt;The underlying probability distribution when the variance is known (scenario 1) is the normal distribution, while the probability distribution in the case where the variance is unknown (scenario 2) is the Student’s t distribution. This difference is partially explained by the fact that when the variance of the population is unknown, there is more “uncertainty” in the data, so we need to use the Student’s t distribution instead of the normal distribution.&lt;/p&gt;
&lt;p&gt;Note that when the sample size is large (usually when &lt;em&gt;n &amp;gt; 30&lt;/em&gt;), the Student’s t distribution tends to a normal distribution. Using a normal distribution when the variance is known and a Student’s t distribution when the variance is unknown also applies to a &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;t-test for two samples&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;how-to-compute-the-one-sample-t-test-in-r&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How to compute the one-sample t-test in R?&lt;/h1&gt;
&lt;p&gt;A good practice before doing t-tests in R is to visualize the data thanks to a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#boxplot&#34;&gt;boxplot&lt;/a&gt; (or eventually a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt; or a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#density-plot&#34;&gt;density plot&lt;/a&gt;). A boxplot gives a first indication on the location of the sample, and thus, a first indication on whether the null hypothesis is likely to be rejected or not. However, even if a boxplot or a density plot is great in showing the distribution of a sample, only a sound statistical test will confirm our first impression.&lt;/p&gt;
&lt;p&gt;After a visualization of the data, we replicate in R the results found by hand. Note that we use the same data, the same assumptions and the same question for both scenarios to facilitate the comparison between the tests performed by hand and in R.&lt;/p&gt;
&lt;div id=&#34;scenario-1-variance-of-the-population-is-known-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 1: variance of the population is known&lt;/h2&gt;
&lt;p&gt;For the first scenario, suppose the data below. Moreover, suppose that the population variance &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2 = 1\)&lt;/span&gt; and that we would like to test whether the population mean is different from 0.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat1 &amp;lt;- data.frame(
  value = c(0.9, -0.8, 1.3, -0.3, 1.7)
)

dat1&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   value
## 1   0.9
## 2  -0.8
## 3   1.3
## 4  -0.3
## 5   1.7&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggplot2)

ggplot(dat1) +
  aes(y = value) +
  geom_boxplot() +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r_files/figure-html/unnamed-chunk-3-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Note that you can use the &lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#esquisse&#34;&gt;&lt;code&gt;{esquisse}&lt;/code&gt; RStudio addin&lt;/a&gt; if you want to draw a boxplot with the &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;package &lt;code&gt;{ggplot2}&lt;/code&gt;&lt;/a&gt; without writing the code yourself. If you prefer the default graphics, use the &lt;code&gt;boxplot()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;boxplot(dat1$value)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r_files/figure-html/unnamed-chunk-4-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The boxplot shows that the distribution of the sample is not distant from 0 (the hypothesized value), so we tend to believe that we will not be able to reject the null hypothesis that the population mean is equal to 0. However, only a formal statistical test will confirm this belief.&lt;/p&gt;
&lt;p&gt;Below a function to perform a t-test with a known population variance, with arguments accepting the sample (&lt;code&gt;x&lt;/code&gt;), the variance of the population (&lt;code&gt;V&lt;/code&gt;), the mean under the null hypothesis (&lt;code&gt;m0&lt;/code&gt;, default is &lt;code&gt;0&lt;/code&gt;), the significance level (&lt;code&gt;alpha&lt;/code&gt;, default is &lt;code&gt;0.05&lt;/code&gt;) and the alternative (&lt;code&gt;alternative&lt;/code&gt;, one of &lt;code&gt;&#34;two.sided&#34;&lt;/code&gt; (default), &lt;code&gt;&#34;less&#34;&lt;/code&gt; or &lt;code&gt;&#34;greater&#34;&lt;/code&gt;):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;t.test2 &amp;lt;- function(x, V, m0 = 0, alpha = 0.05, alternative = &amp;quot;two.sided&amp;quot;) {
  M &amp;lt;- mean(x)
  n &amp;lt;- length(x)
  sigma &amp;lt;- sqrt(V)
  S &amp;lt;- sqrt(V / n)
  statistic &amp;lt;- (M - m0) / S
  p &amp;lt;- if (alternative == &amp;quot;two.sided&amp;quot;) {
    2 * pnorm(abs(statistic), lower.tail = FALSE)
  } else if (alternative == &amp;quot;less&amp;quot;) {
    pnorm(statistic, lower.tail = TRUE)
  } else {
    pnorm(statistic, lower.tail = FALSE)
  }
  LCL &amp;lt;- (M - S * qnorm(1 - alpha / 2))
  UCL &amp;lt;- (M + S * qnorm(1 - alpha / 2))
  value &amp;lt;- list(mean = M, m0 = m0, sigma = sigma, statistic = statistic, p.value = p, LCL = LCL, UCL = UCL, alternative = alternative)
  # print(sprintf(&amp;quot;P-value = %g&amp;quot;,p))
  # print(sprintf(&amp;quot;Lower %.2f%% Confidence Limit = %g&amp;quot;,
  #               alpha, LCL))
  # print(sprintf(&amp;quot;Upper %.2f%% Confidence Limit = %g&amp;quot;,
  #               alpha, UCL))
  return(value)
}

test &amp;lt;- t.test2(dat1$value,
  V = 1
)
test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $mean
## [1] 0.56
## 
## $m0
## [1] 0
## 
## $sigma
## [1] 1
## 
## $statistic
## [1] 1.252198
## 
## $p.value
## [1] 0.2104977
## 
## $LCL
## [1] -0.3165225
## 
## $UCL
## [1] 1.436523
## 
## $alternative
## [1] &amp;quot;two.sided&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output above recaps all the information needed to perform the test: the test statistic, the &lt;em&gt;p&lt;/em&gt;-value, the alternative used, the sample mean, the hypothesized value and the population variance (compare these results found in R with the results found by hand).&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value can be extracted as usual:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$p.value&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.2104977&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.21 so at the 5% significance level we do not reject the null hypothesis. There is no sufficient evidence in the data to reject the hypothesis that the population mean is equal to 0. This result confirms what we found by hand.&lt;/p&gt;
&lt;p&gt;Note that a similar function exists in the &lt;code&gt;{BSDA}&lt;/code&gt; package:&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(BSDA)

z.test(dat1$value,
  alternative = &amp;quot;two.sided&amp;quot;,
  mu = 0,
  sigma.x = 1,
  conf.level = 0.95
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	One-sample z-Test
## 
## data:  dat1$value
## z = 1.2522, p-value = 0.2105
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
##  -0.3165225  1.4365225
## sample estimates:
## mean of x 
##      0.56&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you are unfamiliar with the concept of &lt;em&gt;p&lt;/em&gt;-value, I invite you to read my &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/#a-note-on-p-value-and-significance-level-alpha&#34;&gt;note on &lt;em&gt;p&lt;/em&gt;-value and significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;To sum up&lt;/strong&gt; what have been said in that article about &lt;em&gt;p&lt;/em&gt;-value and significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If the &lt;em&gt;p&lt;/em&gt;-value is smaller than the predetermined significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; (usually 5%) so if &lt;em&gt;p&lt;/em&gt;-value &amp;lt; 0.05, we reject the null hypothesis&lt;/li&gt;
&lt;li&gt;If the &lt;em&gt;p&lt;/em&gt;-value is greater than or equal to the predetermined significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt; (usually 5%) so if &lt;em&gt;p&lt;/em&gt;-value &lt;span class=&#34;math inline&#34;&gt;\(\ge\)&lt;/span&gt; 0.05, we do &lt;strong&gt;not reject&lt;/strong&gt; the null hypothesis&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This applies to all statistical tests without exception. Of course, the null and alternative hypotheses change depending on the test.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;scenario-2-variance-of-the-population-is-unknown-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Scenario 2: variance of the population is unknown&lt;/h2&gt;
&lt;p&gt;For the second scenario, suppose the data below. Moreover, suppose that the variance in the population is unknown and that we would like to test whether the population mean is larger than 5.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat2 &amp;lt;- data.frame(
  value = c(7.9, 5.8, 6.3, 7.3, 6.7)
)

dat2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   value
## 1   7.9
## 2   5.8
## 3   6.3
## 4   7.3
## 5   6.7&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat2) +
  aes(y = value) +
  geom_boxplot() +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r_files/figure-html/unnamed-chunk-8-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Unlike the previous scenario, the box is quite distant from the hypothesized value of 5. From this boxplot, we can expect the test to reject the null hypothesis of the population mean being equal to 5. Nonetheless, only a formal statistical test will confirm this expectation.&lt;/p&gt;
&lt;p&gt;There is a function in R, and it is simply the &lt;code&gt;t.test()&lt;/code&gt; function. This version of the test is actually the “standard” t-test for one-sample. Note that in our case the alternative hypothesis is &lt;span class=&#34;math inline&#34;&gt;\(H_1: \mu &amp;gt; 5\)&lt;/span&gt; so we need to add the arguments &lt;code&gt;mu = 5&lt;/code&gt; and &lt;code&gt;alternative = &#34;greater&#34;&lt;/code&gt; to the function because the default arguments are &lt;code&gt;mu = 0&lt;/code&gt; and the two-sided test:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- t.test(dat2$value,
  mu = 5,
  alternative = &amp;quot;greater&amp;quot;
)

test&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## 	One Sample t-test
## 
## data:  dat2$value
## t = 4.8809, df = 4, p-value = 0.004078
## alternative hypothesis: true mean is greater than 5
## 95 percent confidence interval:
##  6.013814      Inf
## sample estimates:
## mean of x 
##       6.8&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output above recaps all the information needed to perform the test: the name of the test, the test statistic, the degrees of freedom, the &lt;em&gt;p&lt;/em&gt;-value, the alternative used, the hypothesized value and the sample mean (compare these results found in R with the results found by hand).&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value can be extracted as usual:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$p.value&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.004077555&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is 0.004 so at the 5% significance level we reject the null hypothesis.&lt;/p&gt;
&lt;p&gt;Unlike the first scenario, the &lt;em&gt;p&lt;/em&gt;-value in this scenario is below 5% so we reject the null hypothesis. At the 5% significance level, we can conclude that the population mean is significantly larger than 5. This result confirms what we found by hand.&lt;/p&gt;
&lt;div id=&#34;confidence-interval&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Confidence interval&lt;/h3&gt;
&lt;p&gt;Note that the confidence interval can be extracted with &lt;code&gt;$conf.int&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$conf.int&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 6.013814      Inf
## attr(,&amp;quot;conf.level&amp;quot;)
## [1] 0.95&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can see that the 95% confidence interval for the population mean is &lt;span class=&#34;math inline&#34;&gt;\([6.01; \infty]\)&lt;/span&gt;, meaning that, at the significance level &lt;span class=&#34;math inline&#34;&gt;\(\alpha = 5\)&lt;/span&gt;%, we reject the null hypothesis as long as the hypothesized value &lt;span class=&#34;math inline&#34;&gt;\(\mu_0\)&lt;/span&gt; is below 6.01, otherwise the null hypothesis cannot be rejected.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;combination-of-plot-and-statistical-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Combination of plot and statistical test&lt;/h2&gt;
&lt;p&gt;After having written this article, I discovered the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package which I believe is worth mentioning here, in particular the &lt;code&gt;gghistostats()&lt;/code&gt; function for one-sample Student’s t-test.&lt;/p&gt;
&lt;p&gt;This function combines a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt;—representing the distribution—and the results of the statistical test displayed in the subtitle of the plot.&lt;/p&gt;
&lt;p&gt;See examples below for scenario 2. Unfortunately, the package does not allow to run the test for scenario 1.&lt;/p&gt;
&lt;div id=&#34;scenario-2-variance-of-the-population-is-unknown-2&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Scenario 2: variance of the population is unknown&lt;/h3&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# load packages
library(ggstatsplot)
library(ggplot2)

# plot with stat test
gghistostats(
  data = dat2, # dataframe from which variable is to be taken
  x = value, # numeric variable whose distribution is of interest
  type = &amp;quot;parametric&amp;quot;, # for student&amp;#39;s t-test
  test.value = 5 # default value is 0
) +
  labs(caption = NULL) # remove caption&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/how-to-perform-a-one-sample-t-test-by-hand-and-in-r_files/figure-html/unnamed-chunk-12-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is displayed after &lt;code&gt;p =&lt;/code&gt; in the subtitle of the plot. Based on this plot and the &lt;em&gt;p&lt;/em&gt;-value being lower than 5% (&lt;em&gt;p&lt;/em&gt;-value = 0.008), we reject the null hypothesis that the population mean is equal to 5.&lt;/p&gt;
&lt;p&gt;Note that, the &lt;em&gt;p&lt;/em&gt;-value is two times as large as the one obtained with the &lt;code&gt;t.test()&lt;/code&gt; function because when we ran &lt;code&gt;t.test()&lt;/code&gt; we specified &lt;code&gt;alternative = &#34;greater&#34;&lt;/code&gt; (i.e., a one-sided test). In our plot with the &lt;code&gt;gghistostats()&lt;/code&gt; function, it is a two-sided test that is performed by default, that is, &lt;code&gt;alternative = &#34;two.sided&#34;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The point of this section was to illustrate how to easily draw plots together with statistical results, which is exactly the aim of the &lt;code&gt;{ggstatsplot}&lt;/code&gt; package. See more details and examples in this &lt;a href=&#34;https://statsandr.com/blog/how-to-do-a-t-test-or-anova-for-many-variables-at-once-in-r-and-communicate-the-results-in-a-better-way/&#34;&gt;article&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;assumptions&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Assumptions&lt;/h1&gt;
&lt;p&gt;As for many &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt;, there are some assumptions that need to be met in order to be able to interpret the results. When one or several assumptions are not met, although it is technically possible to perform these tests, it would be incorrect to interpret the results. Below are the assumptions of the one-sample t-test and how to test them:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Variable type&lt;/strong&gt;: The dependent variable (i.e., the measured variable) must be measured on a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#continuous&#34;&gt;continuous&lt;/a&gt; or &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#ordinal&#34;&gt;ordinal scale&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Independence&lt;/strong&gt;: The data, collected from a representative and randomly selected portion of the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;population&lt;/a&gt;, should be independent of one another. The assumption of independence is most often verified based on the design of the experiment and on the good control of experimental conditions rather than via a formal test. If you are still unsure about independence based on the experiment design, ask yourself if one observation is related to another (if one observation has an impact on another). If not, it is most likely that you have independent &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;samples&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Normality&lt;/strong&gt;:
&lt;ul&gt;
&lt;li&gt;With a small sample size (usually &lt;span class=&#34;math inline&#34;&gt;\(n &amp;lt; 30\)&lt;/span&gt;), observations should follow a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;&lt;strong&gt;normal distribution&lt;/strong&gt;&lt;/a&gt;. The normality assumption can be tested visually thanks to a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt; and a &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#qq-plot&#34;&gt;QQ-plot&lt;/a&gt;, and/or formally via a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/#normality-test&#34;&gt;normality test&lt;/a&gt; such as the Shapiro-Wilk or Kolmogorov-Smirnov test. Some transformations, such as among others, the logarithm, the square root or the Box-Cox transformation can be applied on the observations to transform you data to better fit the normal distribution. If, even after a transformation, your data still do not follow a normal distribution, the &lt;a href=&#34;https://statsandr.com/blog/one-sample-wilcoxon-test-in-r/&#34;&gt;one-sample Wilcoxon test&lt;/a&gt; (&lt;code&gt;wilcox.test(variable_name, data = dat&lt;/code&gt; in R) can be applied. This non-parametric test is robust to non normal distributions so it does not require normality of the data.&lt;/li&gt;
&lt;li&gt;With a large sample size (&lt;span class=&#34;math inline&#34;&gt;\(n \ge 30\)&lt;/span&gt;), &lt;strong&gt;normality of the data is not required&lt;/strong&gt; (this is a common misconception!). By the &lt;a href=&#34;https://en.wikipedia.org/wiki/Central_limit_theorem&#34; target=&#34;_blank&#34;&gt;central limit theorem&lt;/a&gt;, sample means of large samples are often well-approximated by a normal distribution even if the data are not normally distributed &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-stevens2013intermediate&#34;&gt;Stevens 2013&lt;/a&gt;)&lt;/span&gt;. It is therefore not required to test the normality assumption when the number of observations is large.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Outliers&lt;/strong&gt;: There should be no &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt; in your data. An observation slightly different from the others does not pose a problem, but it starts to be an issue when you have at least one &lt;em&gt;extreme&lt;/em&gt; outlier. In presence of at least one extreme outlier, it is best to transform your data (with the logarithm transformation for instance, as you would do with a non normal distribution) or use the non-parametric &lt;a href=&#34;https://statsandr.com/blog/one-sample-wilcoxon-test-in-r/&#34;&gt;one-sample Wilcoxon test&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to understand how the different versions of the one-sample t-test work and how to perform them by hand and in R.&lt;/p&gt;
&lt;p&gt;If you are interested, here is a &lt;a href=&#34;https://statsandr.com/blog/a-shiny-app-for-inferential-statistics-by-hand/&#34;&gt;Shiny app&lt;/a&gt; to perform these tests by hand easily (you just need to enter your data and select the appropriate version of the test thanks to the sidebar menu). Moreover, read &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;this article&lt;/a&gt; if you would like to know how to compute the Student’s t-test but this time, for two samples—in order to compare two dependent or independent groups—or this &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;article&lt;/a&gt; if you want to use an ANOVA to compare 3 or more groups.&lt;/p&gt;
&lt;p&gt;As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-stevens2013intermediate&#34; class=&#34;csl-entry&#34;&gt;
Stevens, James P. 2013. &lt;em&gt;Intermediate Statistics: A Modern Approach&lt;/em&gt;. Routledge.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;It is a least the case regarding parametric hypothesis tests. A parametric test means that it is based on a theoretical statistical distribution, which depends on some defined parameters. In the case of the one-sample t-test, it is based on the Student’s t distribution with a single parameter, the degrees of freedom (&lt;span class=&#34;math inline&#34;&gt;\(df = n - 1\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is the sample size), or the normal distribution.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Thanks gmacar for pointing it out to me.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>The 9 concepts and formulas in probability that every data scientist should know</title>
      <link>https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/</link>
      <pubDate>Tue, 03 Mar 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#what-is-probability&#34; id=&#34;toc-what-is-probability&#34;&gt;What is probability?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#a-probability-is-always-between-0-and-1&#34; id=&#34;toc-a-probability-is-always-between-0-and-1&#34;&gt;1. A probability is always between 0 and 1&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#compute-a-probability&#34; id=&#34;toc-compute-a-probability&#34;&gt;2. Compute a probability&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#complement-of-an-event&#34; id=&#34;toc-complement-of-an-event&#34;&gt;3. Complement of an event&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#union-of-two-events&#34; id=&#34;toc-union-of-two-events&#34;&gt;4. Union of two events&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#intersection-of-two-events&#34; id=&#34;toc-intersection-of-two-events&#34;&gt;5. Intersection of two events&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#independence-of-two-events&#34; id=&#34;toc-independence-of-two-events&#34;&gt;6. Independence of two events&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conditional-probability&#34; id=&#34;toc-conditional-probability&#34;&gt;7. Conditional probability&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#bayes-theorem&#34; id=&#34;toc-bayes-theorem&#34;&gt;Bayes’ theorem&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#example&#34; id=&#34;toc-example&#34;&gt;Example&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#accuracy-measures&#34; id=&#34;toc-accuracy-measures&#34;&gt;8. Accuracy measures&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#false-negatives&#34; id=&#34;toc-false-negatives&#34;&gt;False negatives&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#false-positives&#34; id=&#34;toc-false-positives&#34;&gt;False positives&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#sensitivity&#34; id=&#34;toc-sensitivity&#34;&gt;Sensitivity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#specificity&#34; id=&#34;toc-specificity&#34;&gt;Specificity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#positive-predictive-value&#34; id=&#34;toc-positive-predictive-value&#34;&gt;Positive predictive value&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#negative-predictive-value&#34; id=&#34;toc-negative-predictive-value&#34;&gt;Negative predictive value&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#counting-techniques&#34; id=&#34;toc-counting-techniques&#34;&gt;9. Counting techniques&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#multiplication&#34; id=&#34;toc-multiplication&#34;&gt;Multiplication&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#example-1&#34; id=&#34;toc-example-1&#34;&gt;Example&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#permutation&#34; id=&#34;toc-permutation&#34;&gt;Permutation&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#example-2&#34; id=&#34;toc-example-2&#34;&gt;Example&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand&#34; id=&#34;toc-by-hand&#34;&gt;By hand&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#in-r&#34; id=&#34;toc-in-r&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#combination&#34; id=&#34;toc-combination&#34;&gt;Combination&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#example-3&#34; id=&#34;toc-example-3&#34;&gt;Example&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand-1&#34; id=&#34;toc-by-hand-1&#34;&gt;By hand&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#in-r-1&#34; id=&#34;toc-in-r-1&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/the-7-formulas-in-probability-that-every-data-scientist-should-know_files/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;what-is-probability&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;What is probability?&lt;/h1&gt;
&lt;p&gt;A probability is a number that reflects the &lt;strong&gt;chance that a particular event will occur&lt;/strong&gt;. In other words, it quantifies (on a scale from 0 to 1, or from 0% to 100%) &lt;strong&gt;how likely an event is to occur&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Probability is a branch of mathematics that provides models to describe random processes. These mathematical tools allow to establish theoretical models for random phenomena and to use them to make predictions. Like every model, the probabilistic model is a simplification of the world. However, the model is useful as soon as it captures the essential features.&lt;/p&gt;
&lt;p&gt;In this article, we present 9 fundamental formulas and concepts in probability that every data scientist should understand and master in order to appropriately handle any project involving probabilities.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;a-probability-is-always-between-0-and-1&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;1. A probability is always between 0 and 1&lt;/h1&gt;
&lt;p&gt;The probability of an event is always between 0 and 1 (or 0% and 100%). If we denote the probability that an event A (which could be any event) occurs by &lt;span class=&#34;math inline&#34;&gt;\(P(A)\)&lt;/span&gt;, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[0 \le P(A) \le 1\]&lt;/span&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If an event is impossible: &lt;span class=&#34;math inline&#34;&gt;\(P(A) = 0\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;If an event is certain: &lt;span class=&#34;math inline&#34;&gt;\(P(A) = 1\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For example, throwing a 7 with a standard six-sided dice (with faces ranging from 1 to 6) is impossible so its probability is equal to 0. Throwing head &lt;em&gt;or&lt;/em&gt; tail with a coin is certain, so its probability is equal to 1.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;compute-a-probability&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;2. Compute a probability&lt;/h1&gt;
&lt;p&gt;If the elements of a sample space (the set of all possible results of a randomized experiment) are equiprobable (= all elements have the same probability), then the probability of an event occurring is equal to the number of favourable cases (number of ways it can happen) divided by the number of possible cases (total number of outcomes):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A) = \frac{\text{number of favourable cases}}{\text{number of possible cases}}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For example, all numbers of a six-sided dice are equiprobable since they all have the same probability of occurring. The probability of rolling a 3 with a dice is thus&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(3) = \frac{\text{number of favourable cases}}{\text{number of possible cases}} = \frac{1}{6}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;because there is only one favourable case (there is only one face with a 3 on it), and there are 6 possible cases (because there are 6 faces altogether).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;complement-of-an-event&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;3. Complement of an event&lt;/h1&gt;
&lt;p&gt;The probability of the complement (or opposite) of an event is:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(\text{not A}) = P(\bar{A}) = 1 - P(A)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For instance, the probability of &lt;em&gt;not&lt;/em&gt; throwing a 3 with a dice is:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(\bar{A}) = 1 - P(A) = 1 - \frac{1}{6} = \frac{5}{6}\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;union-of-two-events&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;4. Union of two events&lt;/h1&gt;
&lt;p&gt;The probability of the union of two events is the probability of either occurring:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
P(\text{A or B)} &amp;amp;= P(A \cup B) \\
&amp;amp;= P(A) + P(B) - P(A \cap B)
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Suppose that the probability of a fire breaking out in two houses in a given year is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;in house A: 60%, so &lt;span class=&#34;math inline&#34;&gt;\(P(A) = 0.6\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;in house B: 45%, so &lt;span class=&#34;math inline&#34;&gt;\(P(B) = 0.45\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;in at least one of the two houses: 80%, so &lt;span class=&#34;math inline&#34;&gt;\(P(A \cup B) = 0.8\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Graphically we have&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/the-7-formulas-in-probability-that-every-data-scientist-should-know_files/figure-html/unnamed-chunk-1-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The probability of a fire breaking out in house A &lt;strong&gt;or&lt;/strong&gt; house B is&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A \cup B) = P(A) + P(B) - P(A \cap B)\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[= 0.6 + 0.45 - 0.25 = 0.8\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;By summing &lt;span class=&#34;math inline&#34;&gt;\(P(A)\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(P(B)\)&lt;/span&gt;, the intersection of A and B, i.e. &lt;span class=&#34;math inline&#34;&gt;\(P(A \cap B)\)&lt;/span&gt;, is counted twice. This is the reason we subtract it to count it only once.&lt;/p&gt;
&lt;p&gt;If two events are mutually exclusive (i.e., two events that cannot occur simultaneously), the probability of both events occurring &lt;span class=&#34;math inline&#34;&gt;\(P(A \cap B)\)&lt;/span&gt; is equal to 0, so the above formula becomes&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A \cup B) = P(A) + P(B)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For example, the event “rolling a 3” and the event “rolling a 6” on a six-sided dice are two mutually exclusive events since they cannot both occur at the same time. Since their joint probability is equal to 0, the probability of rolling a 3 or 6 on a six-sided dice is&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(3 \cup 6) = P(3) + P(6) = \frac{1}{6} + \frac{1}{6} = \frac{1}{3}\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;intersection-of-two-events&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;5. Intersection of two events&lt;/h1&gt;
&lt;p&gt;&lt;strong&gt;If two events are independent&lt;/strong&gt;, the probability of the intersection of the two events (i.e., the joint probability) is the probability of the two events occurring:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(\text{A and B)} = P(A \cap B) = P(A) \cdot P(B)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;For instance, if two coins are flipped, the probability of both coins being tails is&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(T_1 \cap T_2) = P(T_1) \cdot P(T_2) = \frac{1}{2} \cdot \frac{1}{2} = \frac{1}{4}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(T_1\)&lt;/span&gt; (&lt;span class=&#34;math inline&#34;&gt;\(T_2\)&lt;/span&gt;) denotes the event that the first (second) coin is tail.&lt;/p&gt;
&lt;p&gt;Note that &lt;span class=&#34;math inline&#34;&gt;\(P(A \cap B) = P(B \cap A)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;If two events are mutually exclusive, their joint probability is equal to 0:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A \cap B) = 0\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;independence-of-two-events&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;6. Independence of two events&lt;/h1&gt;
&lt;p&gt;Another important concept in probability is the independence of two events. Formally, the events A and B are independent if and only if&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A \cap B) = P(A) \cdot P(B)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;If the equality holds, the two events are said to be independent, otherwise the two events are said to be dependent.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In the example of the two coins:&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(T_1 \cap T_2) = \frac{1}{4}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;and&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(T_1) \cdot P(T_2) = \frac{1}{2} \cdot \frac{1}{2} = \frac{1}{4}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;so the following equality holds&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(T_1 \cap T_2) = P(T_1) \cdot P(T_2) = \frac{1}{4}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The two events are thus independent, denoted &lt;span class=&#34;math inline&#34;&gt;\(T_1{\perp\!\!\!\perp}T_2\)&lt;/span&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In the example of the fire breaking out in two houses (see &lt;a href=&#34;https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/#union-of-two-events&#34;&gt;section 4&lt;/a&gt;):&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A \cap B) = 0.25\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;and&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A) \cdot P(B) = 0.6 \cdot 0.45 = 0.27\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;so the following equality does not hold&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A \cap B) \ne P(A) \cdot P(B)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The two events are thus dependent (or not independent), denoted &lt;span class=&#34;math inline&#34;&gt;\(A \not\!\perp\!\!\!\perp B\)&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conditional-probability&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;7. Conditional probability&lt;/h1&gt;
&lt;p&gt;Suppose two events A and B and &lt;span class=&#34;math inline&#34;&gt;\(P(B) &amp;gt; 0\)&lt;/span&gt;. The conditional probability of A given (knowing) B is the likelihood of event A occurring given that event B has occurred:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A | B) = \frac{P(A \cap B)}{P(B)}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[= \frac{P(B \cap A)}{P(B)} \text{ (since } P(A \cap B) = P(B \cap A))\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Note that, in general, the probability of A given B is not equal to the probability of B given A, that is, &lt;span class=&#34;math inline&#34;&gt;\(P(A | B) \ne P(B | A)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;From the formula of the conditional probability, we can derive the multiplicative law:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A | B) = \frac{P(A \cap B)}{P(B)} \text{ (Eq. 1)}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[P(A | B) \cdot P(B) = \frac{P(A \cap B)}{P(B)} \cdot P(B)\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[P(A | B) \cdot P(B) = P(A \cap B) \text{ (multiplicative law)}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;If two events are independent, &lt;span class=&#34;math inline&#34;&gt;\(P(A \cap B) = P(A) \cdot P(B)\)&lt;/span&gt;, and:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(P(B) &amp;gt; 0\)&lt;/span&gt;, the conditional probability becomes&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A | B) = \frac{P(A \cap B)}{P(B)}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[P(A | B) = \frac{P(A) \cdot P(B)}{P(B)}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[P(A | B) = P(A) \text{ (Eq. 2)}\]&lt;/span&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(P(A) &amp;gt; 0\)&lt;/span&gt;, the conditional probability becomes&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(B | A) = \frac{P(B \cap A)}{P(A)}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[P(B | A) = \frac{P(B) \cdot P(A)}{P(A)}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[P(B | A) = P(B) \text{ (Eq. 3)}\]&lt;/span&gt;
Equations 2 and 3 mean that knowing that one event occurred does not influence the probability of the outcome of the other event. This is in fact the definition of the independence: if knowing that one event occurred does not help to predict (does not influence) the outcome of the other event, the two events are by essence independent.&lt;/p&gt;
&lt;div id=&#34;bayes-theorem&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Bayes’ theorem&lt;/h2&gt;
&lt;p&gt;From the formulas of the conditional probability and the multiplicative law, we can derive the Bayes’ theorem:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
P(B | A) &amp;amp;= \frac{P(B \cap A)}{P(A)} \\
&amp;amp; \text{(from conditional probability)} \\
&amp;amp;= \frac{P(A \cap B)}{P(A)} \\
&amp;amp; \text{(since } P(A \cap B) = P(B \cap A)) \\
&amp;amp;= \frac{P(A | B) \cdot P(B)}{P(A)} \\
&amp;amp; \text{ (from multiplicative law)}
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;which is equivalent to&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
P(B | A) &amp;amp;= \frac{P(B | A) \cdot P(A)}{P(B)} \\
&amp;amp; \text{(Bayes&amp;#39; theorem)}
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;example&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Example&lt;/h2&gt;
&lt;p&gt;In order to illustrate the conditional probability and the Bayes’ theorem, suppose the following problem:&lt;/p&gt;
&lt;p&gt;In order to determine the presence of a disease in a person, a blood test is performed. When a person has the disease, the test can reveal the disease in 80% of cases. When the disease is not present, the test is negative in 90% of cases. Experience has shown that the probability of the disease being present is 10%. A researcher would like to know the probability that an individual has the disease &lt;em&gt;given that the result of the test is positive&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;To answer this question, the following events are defined:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;P: the test result is positive&lt;/li&gt;
&lt;li&gt;D: the person has the disease&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Moreover, we use a tree diagram to illustrate the statement:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/the-7-formulas-in-probability-that-every-data-scientist-should-know_files/Screenshot%202020-03-03%20at%2013.54.24.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;(The sum of all 4 scenarios must be equal to 1 since these 4 scenarios cover all possible cases.)&lt;/p&gt;
&lt;p&gt;We are looking for the probability that an individual has the disease given that the result of the test is positive, &lt;span class=&#34;math inline&#34;&gt;\(P(D | P)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Following the formula of the conditional probability (Eq. 1) we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(A | B) = \frac{P(A \cap B)}{P(B)}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In terms of our problem:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(D | P) = \frac{P(D \cap P)}{P(P)}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[P(D | P) = \frac{0.08}{P(P)} \text{ (Eq. 4)}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;From the tree diagram, we can see that a positive test result is possible under two scenarios:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;when a person has the disease, or&lt;/li&gt;
&lt;li&gt;when the person does not actually have the disease (because the test is not always correct).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In order to find the probability of a positive test result, &lt;span class=&#34;math inline&#34;&gt;\(P(P)\)&lt;/span&gt;, we need to sum up those two scenarios:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
P(P) &amp;amp;= P(D \cap P) + P(\bar{D} \cap P) \\
&amp;amp;= 0.08 + 0.09 \\
&amp;amp;= 0.17
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Eq. 4 then becomes&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(D | P) = \frac{0.08}{0.17} = 0.4706\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The probability of having the disease given that the result of the test is positive is only 47.06%. This means that in this specific case (with the same percentages), an individual with a positive test has less than 1 chance out of 2 of having the disease!&lt;/p&gt;
&lt;p&gt;This relatively small percentage is due to the facts that the disease is quite rare (only 10% of the population is affected) and that the test is not always correct (sometimes it detects the disease although it is not present, and sometimes it does not detect it although it is present).&lt;/p&gt;
&lt;p&gt;As a consequence, a higher percentage of healthy people have a positive result (9%) compared to the percentage of people who have a positive result and who actually have the disease (8%). This explains why several diagnostic tests are often performed before announcing the diagnosis, especially for rare diseases.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;accuracy-measures&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;8. Accuracy measures&lt;/h1&gt;
&lt;p&gt;Based on the example of the disease and the diagnostic test presented above, we explain the most common accuracy measures:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;False negative (number and rate)&lt;/li&gt;
&lt;li&gt;False positive (number and rate)&lt;/li&gt;
&lt;li&gt;Sensitivity&lt;/li&gt;
&lt;li&gt;Specificity&lt;/li&gt;
&lt;li&gt;Positive predictive value&lt;/li&gt;
&lt;li&gt;Negative predictive value&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Before diving into the details of these accuracy measures, here is an overview of the measures and the tree diagram with the labels added for each of the 4 scenarios:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/the-7-formulas-in-probability-that-every-data-scientist-should-know_files/the-7-concepts-and-formulas-in-probability-that-every-data-scientist-should-know.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Adapted from Wikipedia&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/the-7-formulas-in-probability-that-every-data-scientist-should-know_files/Screenshot%202020-03-03%20at%2015.53.19.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;false-negatives&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;False negatives&lt;/h2&gt;
&lt;p&gt;The false negatives (FN) are the number of people incorrectly labeled as &lt;strong&gt;not&lt;/strong&gt; having the disease or the condition, when in reality it is present. It is like telling a women who is 7 months pregnant that she is not pregnant.&lt;/p&gt;
&lt;p&gt;From the tree diagram, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[FN = P(D \cap \bar{P}) = 0.02\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Moreover, the false negative &lt;strong&gt;rate&lt;/strong&gt; (&lt;em&gt;FNR&lt;/em&gt;) is defined as&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
FNR &amp;amp;= \frac{FN}{FN + TP} \\
&amp;amp;= P(\bar{P} | D) \\
&amp;amp;= \frac{P(\bar{P} \cap D)}{P(D)} \\
&amp;amp;= \frac{0.02}{0.08 + 0.02} \\
&amp;amp;= 0.2
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;false-positives&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;False positives&lt;/h2&gt;
&lt;p&gt;The false positives (FP) are the number of people incorrectly labeled as having the disease or the condition, when in reality it is &lt;strong&gt;not&lt;/strong&gt; present. It is like telling a man he is pregnant.&lt;/p&gt;
&lt;p&gt;From the tree diagram, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[FP = P(\bar{D} \cap P) = 0.09\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Moreover, the false positive &lt;strong&gt;rate&lt;/strong&gt; (&lt;em&gt;FPR&lt;/em&gt;) is defined as&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
FPR &amp;amp;= \frac{FP}{FP + TN} \\
&amp;amp;= P(P | \bar{D}) \\
&amp;amp;= \frac{P(P \cap \bar{D})}{P(\bar{D})} \\
&amp;amp;= \frac{0.09}{0.09 + 0.81} \\
&amp;amp;= 0.1
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;sensitivity&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Sensitivity&lt;/h2&gt;
&lt;p&gt;The sensitivity of a test, also referred as the recall, measures the ability of a test to detect the condition when the condition is present (the percentage of sick people who are correctly identified as having the disease):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[ Sensitivity = \frac{TP}{TP + FN}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;em&gt;TP&lt;/em&gt; is the true positives.&lt;/p&gt;
&lt;p&gt;From the tree diagram, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
Sensitivity &amp;amp;= \frac{TP}{TP + FN} \\
&amp;amp;= P(P|D) \\
&amp;amp;= 0.8
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Note also that &lt;span class=&#34;math inline&#34;&gt;\(1 - sensitivity = FNR\)&lt;/span&gt; (false negative rate).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;specificity&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Specificity&lt;/h2&gt;
&lt;p&gt;The specificity of a test measures the ability of a test to correctly exclude the condition when the condition is absent (the percentage of healthy people who are correctly identified as not having the disease):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[Specificity = \frac{TN}{TN + FP}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;em&gt;TN&lt;/em&gt; is the true negatives.&lt;/p&gt;
&lt;p&gt;From the tree diagram, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
Specificity &amp;amp;= \frac{TN}{TN + FP} \\
&amp;amp;= P(\bar{P} | \bar{D}) \\
&amp;amp;= 0.9
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Note also that &lt;span class=&#34;math inline&#34;&gt;\(1 - specificity = FPR\)&lt;/span&gt; (false positive rate).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;positive-predictive-value&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Positive predictive value&lt;/h2&gt;
&lt;p&gt;The positive predictive value, also referred as the precision, is the proportion of positives that correspond to the presence of the condition, so the proportions of positive results that are true positive results:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[PPV = \frac{TP}{TP+FP}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;From the tree diagram, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
PPV &amp;amp;= \frac{TP}{TP+FP} \\
&amp;amp;= P(D | P) \\
&amp;amp;= \frac{P(D \cap P)}{P(P)} \\
&amp;amp;= \frac{0.08}{0.08+0.09} \\
&amp;amp;= 0.4706
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;negative-predictive-value&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Negative predictive value&lt;/h2&gt;
&lt;p&gt;The negative predictive value is the proportion of negatives that correspond to the absence of the condition, so the proportions of negative results that are true negative results:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[NPV = \frac{TN}{TN + FN}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;From the tree diagram, we have:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
NPV &amp;amp;= \frac{TN}{TN + FN} \\
&amp;amp;= P(\bar{D} | \bar{P}) \\
&amp;amp;= \frac{P(\bar{D} \cap \bar{P})}{P(\bar{P})} \\
&amp;amp;= \frac{0.81}{0.81+0.02} \\
&amp;amp;= 0.9759
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;counting-techniques&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;9. Counting techniques&lt;/h1&gt;
&lt;p&gt;In order to use the formula in &lt;a href=&#34;https://statsandr.com/blog/the-9-concepts-and-formulas-in-probability-that-every-data-scientist-should-know/#compute-a-probability&#34;&gt;section 2&lt;/a&gt;, one must know how to count the number of possible elements (both for favorable and possible cases).&lt;/p&gt;
&lt;p&gt;There are 3 main counting techniques in probability:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Multiplication&lt;/li&gt;
&lt;li&gt;Permutation&lt;/li&gt;
&lt;li&gt;Combination&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;See below how to count the number of possible elements in case of equiprobable results.&lt;/p&gt;
&lt;div id=&#34;multiplication&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Multiplication&lt;/h2&gt;
&lt;p&gt;The multiplication rule is as follows:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\#(A \times B) = (\#A) \times (\#B)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(\#\)&lt;/span&gt; is the number of elements.&lt;/p&gt;
&lt;div id=&#34;example-1&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Example&lt;/h3&gt;
&lt;p&gt;In a restaurant, a customer has to choose a starter, a main course and a dessert. The restaurant offers 2 starters, 3 main courses and 2 desserts. How many different choices are possible?&lt;/p&gt;
&lt;p&gt;There are &lt;span class=&#34;math inline&#34;&gt;\(2 \cdot 3 \cdot 2 = 12\)&lt;/span&gt; different possible choices.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;permutation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Permutation&lt;/h2&gt;
&lt;p&gt;The number of permutations is as follows:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
P^r_n &amp;amp;= n \times (n - 1) \times \cdots \times (n - r + 1) \\
&amp;amp;= \frac{n !}{(n - r)!}
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;with &lt;span class=&#34;math inline&#34;&gt;\(r\)&lt;/span&gt; the length, &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; the number of elements and &lt;span class=&#34;math inline&#34;&gt;\(r \le n\)&lt;/span&gt;. Note that &lt;span class=&#34;math inline&#34;&gt;\(0! = 1\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(k! = k \times (k - 1) \times (k - 2) \times \cdots \times 2 \times 1\)&lt;/span&gt; if &lt;span class=&#34;math inline&#34;&gt;\(k = 1, 2, \dots\)&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The order is important in permutations!&lt;/p&gt;
&lt;div id=&#34;example-2&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Example&lt;/h3&gt;
&lt;p&gt;Count the permutations of length 2 of the set &lt;span class=&#34;math inline&#34;&gt;\(A = \{a, b, c, d\}\)&lt;/span&gt;, without a letter being repeated. How many permutations do you find?&lt;/p&gt;
&lt;div id=&#34;by-hand&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;By hand&lt;/h4&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P^4_2 = \frac{4!}{(4-2)!} = \frac{4\cdot3\cdot2\cdot1}{2\cdot1} = 12\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;In R&lt;/h4&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(gtools)

x &amp;lt;- c(&amp;quot;a&amp;quot;, &amp;quot;b&amp;quot;, &amp;quot;c&amp;quot;, &amp;quot;d&amp;quot;)

# See all different permutations
perms &amp;lt;- permutations(
  n = 4, r = 2, v = x,
  repeats.allowed = FALSE
)
perms&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       [,1] [,2]
##  [1,] &amp;quot;a&amp;quot;  &amp;quot;b&amp;quot; 
##  [2,] &amp;quot;a&amp;quot;  &amp;quot;c&amp;quot; 
##  [3,] &amp;quot;a&amp;quot;  &amp;quot;d&amp;quot; 
##  [4,] &amp;quot;b&amp;quot;  &amp;quot;a&amp;quot; 
##  [5,] &amp;quot;b&amp;quot;  &amp;quot;c&amp;quot; 
##  [6,] &amp;quot;b&amp;quot;  &amp;quot;d&amp;quot; 
##  [7,] &amp;quot;c&amp;quot;  &amp;quot;a&amp;quot; 
##  [8,] &amp;quot;c&amp;quot;  &amp;quot;b&amp;quot; 
##  [9,] &amp;quot;c&amp;quot;  &amp;quot;d&amp;quot; 
## [10,] &amp;quot;d&amp;quot;  &amp;quot;a&amp;quot; 
## [11,] &amp;quot;d&amp;quot;  &amp;quot;b&amp;quot; 
## [12,] &amp;quot;d&amp;quot;  &amp;quot;c&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Count the number of permutations
nrow(perms)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 12&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;combination&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Combination&lt;/h2&gt;
&lt;p&gt;The number of combinations is as follows:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\begin{align}
C^r_n &amp;amp;= \frac{P^r_n}{r!} \\
&amp;amp;= \frac{n !}{r!(n - r)!} \\
&amp;amp;= {n \choose r} \\
&amp;amp;= \frac{n}{r} \times \frac{n - 1}{r - 1} \times \dots \times \frac{n - r + 1}{1}
\end{align}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;with &lt;span class=&#34;math inline&#34;&gt;\(r\)&lt;/span&gt; the length, &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; the number of elements and &lt;span class=&#34;math inline&#34;&gt;\(r \le n\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;The order is &lt;strong&gt;not&lt;/strong&gt; important in combinations!&lt;/p&gt;
&lt;div id=&#34;example-3&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Example&lt;/h3&gt;
&lt;p&gt;In a family of 5 children, what is the probability that there are 3 girls and 2 boys? Assume that the probabilities of giving birth to a girl and a boy are equal.&lt;/p&gt;
&lt;div id=&#34;by-hand-1&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;By hand&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Count of 3 girls and 2 boys (favourable cases): &lt;span class=&#34;math inline&#34;&gt;\(C^3_5 = {5 \choose 3} = \frac{5!}{3!(5-3)!} = 10\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Count of possible cases: &lt;span class=&#34;math inline&#34;&gt;\(2^5 = 32\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(\Rightarrow P(3 \text{ girls and 2 boys}) = \frac{\text{# of favourable cases}}{\text{# of possible cases}}\)&lt;/span&gt; &lt;span class=&#34;math display&#34;&gt;\[= \frac{10}{32} = 0.3125\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r-1&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;In R&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Count of 3 girls and 2 boys:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;choose(n = 5, k = 3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 10&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;Count of possible cases:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;2^5&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 32&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Probability of 3 girls and 2 boys:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;choose(n = 5, k = 3) / 2^5&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.3125&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to understand the most important formulas and concepts from probability theory.&lt;/p&gt;
&lt;p&gt;As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Getting started in R markdown</title>
      <link>https://statsandr.com/blog/getting-started-in-r-markdown/</link>
      <pubDate>Tue, 18 Feb 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/getting-started-in-r-markdown/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#r-markdown-what-why-and-how&#34; id=&#34;toc-r-markdown-what-why-and-how&#34;&gt;R Markdown: what, why and how?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#before-you-start&#34; id=&#34;toc-before-you-start&#34;&gt;Before you start&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#components-of-a-.rmd-file&#34; id=&#34;toc-components-of-a-.rmd-file&#34;&gt;Components of a &lt;code&gt;.Rmd&lt;/code&gt; file&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#yaml-header&#34; id=&#34;toc-yaml-header&#34;&gt;YAML header&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#code-chunks&#34; id=&#34;toc-code-chunks&#34;&gt;Code chunks&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#text&#34; id=&#34;toc-text&#34;&gt;Text&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#code-inside-text&#34; id=&#34;toc-code-inside-text&#34;&gt;Code inside text&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#highlight-text-like-it-is-code&#34; id=&#34;toc-highlight-text-like-it-is-code&#34;&gt;Highlight text like it is code&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#images&#34; id=&#34;toc-images&#34;&gt;Images&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#tables&#34; id=&#34;toc-tables&#34;&gt;Tables&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#additional-notes-and-useful-resources&#34; id=&#34;toc-additional-notes-and-useful-resources&#34;&gt;Additional notes and useful resources&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/getting-started-in-r-markdown.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;If you have spent some time writing code in R, you probably have heard of generating dynamic reports incorporating R code, R outputs (results) and text or comments. In this article, I will explain how R Markdown works and give you the basic elements you need to get started easily in the production of these dynamic reports.&lt;/p&gt;
&lt;div id=&#34;r-markdown-what-why-and-how&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;R Markdown: what, why and how?&lt;/h1&gt;
&lt;p&gt;R Markdown allows to generate a report (most of the time in PDF, HTML, Word or as a beamer presentation) that is automatically generated from a file written within RStudio. The generated documents can serve as a neat record of your analysis that can be shared and published in a detailed and complete report. Even if you never expect to present the results to someone else, it can also be used as a personal notebook to look back so you can see what you did at that time. A R Markdown file has the extension &lt;code&gt;.Rmd&lt;/code&gt;, while a R script file has the extension &lt;code&gt;.R&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The first main advantage of using R Markdown over R is that, in a R Markdown document, you can combine three important parts of any statistical analysis:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;R code to show how the analyses have been done. For instance, the data and the functions you used. This allows readers to follow your code and to check that the analyses were correctly performed.&lt;/li&gt;
&lt;li&gt;Results of the code, that is, the output of your analyses. For example, the output of your linear model, plots, or results of the hypothesis test you just coded. This allows readers to see the results of your analyses.&lt;/li&gt;
&lt;li&gt;Text, comments and interpretations of the results. For instance, after computing the main &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics&lt;/a&gt; and plotting some graphs, you can interpret them in the context of your problem and highlight important findings. This enables readers to understand your results thanks to your interpretations and your comments, delivered as if you wrote a document explaining your work.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Another advantage of R Markdown is that the reports are dynamic and reproducible by anyone who has access to the &lt;code&gt;.Rmd&lt;/code&gt; file (and the data if external data are used of course), making it perfectly suited to collaboration and dissemination of results. By dynamic, we mean that if your data changes, your results and your interpretations will change accordingly, without any work from your side.&lt;/p&gt;
&lt;p&gt;The production of the reports is done in two stages:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;The &lt;code&gt;.Rmd&lt;/code&gt; file which contains blocks of R code (called chunks) and text is provided to the &lt;code&gt;{knitr}&lt;/code&gt; package which will execute the R code to get the output, and create a document in markdown (&lt;code&gt;.md&lt;/code&gt;) format. This document then contains the R code, the results (or outputs), and the text.&lt;/li&gt;
&lt;li&gt;This &lt;code&gt;.md&lt;/code&gt; file is then converted to the desired format (HTML, PDF or Word), by the &lt;code&gt;markdown&lt;/code&gt; package based on pandoc (i.e., a document conversion tool).&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div id=&#34;before-you-start&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Before you start&lt;/h1&gt;
&lt;p&gt;To create a new R Markdown document (&lt;code&gt;.Rmd&lt;/code&gt;), you first need to install and load the following packages:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;install.packages(c(&amp;quot;knitr&amp;quot;, &amp;quot;rmarkdown&amp;quot;, &amp;quot;markdown&amp;quot;))

library(knitr)
library(rmarkdown)
library(markdown)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then click on File -&amp;gt; New File -&amp;gt; R Markdown or click on the small white sheet with a green cross in the top left corner and select &lt;code&gt;R Markdown&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Screenshot%202020-02-17%20at%2020.15.02.png&#34; alt=&#34;Create a new R Markdown document&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Create a new R Markdown document&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;A window will open, choose the title and the author and click on OK. The default output format is HTML. It can be changed later to PDF or Word.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Screenshot%202020-02-17%20at%2020.39.46.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;After you have clicked on OK, a new &lt;code&gt;.Rmd&lt;/code&gt; file which serves as example has been created. We are going to use this file as starting point to our more complex and more personalized file.&lt;/p&gt;
&lt;p&gt;To compile your R Markdown document into a HTML document, click on the &lt;code&gt;Knit&lt;/code&gt; button located at the top:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Screenshot%202020-02-17%20at%2020.49.02.png&#34; alt=&#34;Knit a R Markdown document&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Knit a R Markdown document&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;A preview of the HTML report appears and it is also saved in your working directory (see a reminder of what is a &lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/&#34;&gt;working directory&lt;/a&gt;).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;components-of-a-.rmd-file&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Components of a &lt;code&gt;.Rmd&lt;/code&gt; file&lt;/h1&gt;
&lt;p&gt;Below the main components of a R Markdown document:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Components%20of%20a%20R%20Markdown%20document.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;These components are detailed in the following sections.&lt;/p&gt;
&lt;div id=&#34;yaml-header&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;YAML header&lt;/h2&gt;
&lt;p&gt;A &lt;code&gt;.Rmd&lt;/code&gt; file starts with the YAML header, enclosed by two series of &lt;code&gt;---&lt;/code&gt;. By default, this includes the title, author, date and the format of the report. If you want to generate the report in a PDF document, replace &lt;code&gt;output: html_document&lt;/code&gt; by&lt;code&gt;output: pdf_document&lt;/code&gt;. These information from the YAML header will appear at the top of the generated report after you compile it (i.e., after knitting the document).&lt;/p&gt;
&lt;p&gt;To add a table of contents to your documents, replace &lt;code&gt;output: html_document&lt;/code&gt; by&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;output:
  html_document:
    toc: true&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here are my usual settings regarding the format of a HTML document (remove everything after &lt;code&gt;number_sections: true&lt;/code&gt; if you render the document in PDF, as PDF documents do not accept these options in the YAML header):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;output:
  html_document:
    toc: true
    toc_depth: 6
    number_sections: true
    toc_float: true
    code_folding: hide
    theme: flatly
    code_download: true&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In addition to adding a table of contents, it sets its depth, adds a section numbering, the table of contents is floating when scrolling down the document, the code is hidden by default, the &lt;code&gt;flatly&lt;/code&gt; theme is used and it adds the possibility to download the &lt;code&gt;.Rmd&lt;/code&gt; document.&lt;/p&gt;
&lt;p&gt;You can visualize your table of contents even before knitting the document, or go directly to a specific section by clicking on the small icon in the top right corner. Your table of contents will appear, click on a section to go to this section in your &lt;code&gt;.Rmd&lt;/code&gt; document:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Screenshot%202020-02-17%20at%2022.15.21.png&#34; alt=&#34;Visualize your table of contents&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Visualize your table of contents&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;In addition to this enhanced table of contents, I usually set the following date in the YAML header:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Screenshot%202020-02-18%20at%2014.15.33.png&#34; alt=&#34;Dynamic date in R Markdown&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Dynamic date in R Markdown&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;This piece of code allows to write the current date, without having to change it myself. This is very convenient for projects that last several weeks or months to always have an updated date at the top of the document.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;code-chunks&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Code chunks&lt;/h2&gt;
&lt;p&gt;Below the YAML header, there is a first code chunk which is used for the setup options of your &lt;strong&gt;entire&lt;/strong&gt; document. It is best to leave it like this at the moment, we can change it later if needed.&lt;/p&gt;
&lt;p&gt;Code chunks in R Markdown documents are used to write R code. Every time you want to include R code, you will need to enclose it with three backwards apostrophes. For instance, to compute the mean of the values 1, 7 and 11, we first need to insert a R code chunk by clicking on the &lt;code&gt;Insert&lt;/code&gt; button located at the top and select R (see below a picture), then we need to write the corresponding code inside the code chunk we just inserted:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Screenshot%202020-02-18%20at%2014.42.48.png&#34; alt=&#34;Insert R code chunk in R Markdown&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Insert R code chunk in R Markdown&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Screenshot%202020-02-17%20at%2021.04.54.png&#34; alt=&#34;Example of code chunk&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Example of code chunk&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;In the example file, you can see that the first R code chunk (except the setup code chunk) includes the function &lt;code&gt;summary()&lt;/code&gt; of the preloaded dataset &lt;code&gt;cars&lt;/code&gt;: &lt;code&gt;summary(cars)&lt;/code&gt;. If you look at the HTML document that is generated from this example file, you will see that the summary measures are displayed just after the code chunk.&lt;/p&gt;
&lt;p&gt;The next code chunk in this example file is &lt;code&gt;plot(pressure)&lt;/code&gt;, which will produce a plot. Try writing other R codes and knit (i.e., compile the document by clicking on the knit button) the document to see if your code is generated correctly.&lt;/p&gt;
&lt;p&gt;If you already wrote code in a R script and want to reuse it in your R Markdown document, you can simply copy paste your code inside code chunks. Do not forget to always include your code inside code chunks or R will throw an error when compiling your document.&lt;/p&gt;
&lt;p&gt;As you can see, there are two additional arguments in the code chunk of the plot compared to my code chunk of the mean presented above. The first argument following the letter &lt;code&gt;r&lt;/code&gt; (without comma between the two) is used to set the name of the chunk. In general, do not bother with this, it is mainly used to refer to a specific code chunk. You can remove the name of the chunk, but do not remove the letter &lt;code&gt;r&lt;/code&gt; between the &lt;code&gt;{}&lt;/code&gt; as it tells R that the code that follows corresponds to R code (yes you read it well, that also means you can include code from another programming language, e.g., Python, SQL, etc.).&lt;/p&gt;
&lt;p&gt;After the name of the chunk (after &lt;code&gt;pressure&lt;/code&gt; in the example file), you can see that there is an additional argument: &lt;code&gt;echo = FALSE&lt;/code&gt;. This argument, called an option, indicates that you want to hide the code, and display only the output of the code. Try removing it (or change it to &lt;code&gt;echo = TRUE&lt;/code&gt;), and you will see that after knitting the document, both the code AND the output will appear, while only the results appeared previously.&lt;/p&gt;
&lt;p&gt;You can specify if you want to hide or display the code alongside the output of that code for each code chunk separately, for instance if you want to show the code for some code chunks, but not for others. Alternatively, if you want to always hide/display the code together with the output for the entire document, you can specify it in the setup code chunk located just after the YAML header. The options passed to this setup code chunk will determine the options for all code chunks, except for those that have been specifically modified.&lt;/p&gt;
&lt;p&gt;By default, the only setup option when you open a new R Markdown file is &lt;code&gt;knitr::opts_chunk$set(echo = TRUE)&lt;/code&gt;, meaning that by default, all outputs will be accompanied by its corresponding code. If you want to display only the results without the code for the whole document, replace it by &lt;code&gt;knitr::opts_chunk$set(echo = FALSE)&lt;/code&gt;. Two other options often passed to this setup code chunk are &lt;code&gt;warning = FALSE&lt;/code&gt; and &lt;code&gt;message = FALSE&lt;/code&gt; to prevent warnings and messages to be displayed on the report. If you want to pass several options, do not forget to separate them with a comma:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Screenshot%202020-02-17%20at%2022.05.12.png&#34; alt=&#34;Several options for a code chunk&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Several options for a code chunk&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;You can also choose to display the code, but not the result. For this, pass the option &lt;code&gt;results = &#34;hide&#34;&lt;/code&gt;. Alternatively, with the option &lt;code&gt;include = FALSE&lt;/code&gt;, you can prevent code and results from appearing in the finished file while R still runs the code in order to use it at a later stage. If you want to prevent the code and the results to appear, and do not want R to run the code, use &lt;code&gt;eval = FALSE&lt;/code&gt;. To edit the width and height of figures, use the options &lt;code&gt;fig.width&lt;/code&gt; and &lt;code&gt;fig.height&lt;/code&gt;. Another very interesting option is the &lt;code&gt;tidy = &#39;styler&#39;&lt;/code&gt; option which automatically &lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#styler&#34;&gt;reformats the R code&lt;/a&gt; shown in the output.&lt;/p&gt;
&lt;p&gt;See all options and their description &lt;a href=&#34;https://yihui.org/knitr/options/&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt; or see the list of the default options by running &lt;code&gt;str(knitr::opts_chunk$get())&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tip&lt;/strong&gt;: When writing in R Markdown, you will very often need to insert new R code chunks. To insert a new R code chunk more rapidly, press &lt;code&gt;CTRL + ALT + I&lt;/code&gt; on Windows or &lt;code&gt;command + option + I&lt;/code&gt; on Mac. If you are interested in such shortcuts making you more efficient, see other &lt;a href=&#34;https://statsandr.com/blog/tips-and-tricks-in-rstudio-and-r-markdown/&#34;&gt;tips and tricks in R Markdown&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Note that a code chunk can be run without the need to compile the entire document, if you want to check the results of a specific code chunk for instance. In order to run a specific code chunk, select the code and run it as you would do in a R script (&lt;code&gt;.R&lt;/code&gt;), by clicking on run or by pressing &lt;code&gt;CTRL + Enter&lt;/code&gt; on Windows or &lt;code&gt;command + Enter&lt;/code&gt; on Mac. Results of this code chunk will be displayed directly in the R Markdown document, just below the code chunk.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;text&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Text&lt;/h2&gt;
&lt;p&gt;Text can be added everywhere outside code chunks. R Markdown documents use the Markdown syntax for the formatting of the text. In our example file just below the setup code chunk, some text has been inserted. To insert text, you simply write text without any enclosing. Try adding some sentences and knit the document to see how it appears in the HTML document.&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Screenshot%202020-02-18%20at%2014.49.47.png&#34; alt=&#34;Example of text below an example of R code chunk&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Example of text below an example of R code chunk&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;Markdown syntax can be used to change the formatting of your text appearing in the output file, for example to format some text in &lt;em&gt;italics&lt;/em&gt;, in &lt;strong&gt;bold&lt;/strong&gt;, etc. Below some common formatting commands:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Title: &lt;code&gt;# Title&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Subtitle: &lt;code&gt;## Subtitle&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Subsubtitle: &lt;code&gt;### Subsubtitle&lt;/code&gt;. These headings will automatically be included in the table of contents if you included one.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;italics&lt;/em&gt;: &lt;code&gt;*italics*&lt;/code&gt; or &lt;code&gt;_italics_&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;bold&lt;/strong&gt;: &lt;code&gt;**bold**&lt;/code&gt; or &lt;code&gt;__bold__&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/&#34;&gt;Link&lt;/a&gt;: &lt;code&gt;[link](https://statsandr.com/)&lt;/code&gt; (do not forget &lt;code&gt;https://&lt;/code&gt; or &lt;code&gt;http://&lt;/code&gt; if it is an external URL)&lt;/li&gt;
&lt;li&gt;Equations:&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Enclose your equation (written in LaTeX) with one &lt;code&gt;$&lt;/code&gt; to have it in the text:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$A = \pi*r^{2}$&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is a well-know equation &lt;span class=&#34;math inline&#34;&gt;\(A = \pi*r^{2}\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Enclose your LaTeX equation with two &lt;code&gt;$$&lt;/code&gt; to have it centered on a new line:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$$A = \pi*r^{2}$$&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is another well-known equation:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[E = mc^2\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Lists:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Unordered list, item 1: &lt;code&gt;* Unordered list, item 1&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Unordered list, item 2: &lt;code&gt;* Unordered list, item 2&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Ordered list, item 1: &lt;code&gt;1. Ordered list, item 1&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Ordered list, item 2: &lt;code&gt;2. Ordered list, item 2&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&#34;code-inside-text&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Code inside text&lt;/h3&gt;
&lt;p&gt;Before going further, I would like to introduce an important feature of R Markdown. It is often the case that, when writing interpretations or detailing an analysis, we would like to refer to a result directly in our text. For instance, suppose we work on the &lt;code&gt;iris&lt;/code&gt; dataset (preloaded in R). We may want to explain in words, that the mean of the length of the petal is a certain value, while the median is another value.&lt;/p&gt;
&lt;p&gt;Without R Markdown, the user would need to compute the mean and median, and then report it manually. Thanks to R Markdown, it is possible to report these two &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics&lt;/a&gt; directly in the text, without manually encoding it. Even better, if the dataset happens to change because we removed some observations, the mean and median reported in the generated document will change automatically, without any change in the text from our side.&lt;/p&gt;
&lt;p&gt;We can insert results directly in the interpretations (i.e., in the text) by placing a backward apostrophe, the letter &lt;code&gt;r&lt;/code&gt;, a space, the code, and then close it with another backward apostrophe:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Screenshot%202020-03-15%20at%2011.14.50.png&#34; alt=&#34;Inline code in R Markdown&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Inline code in R Markdown&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;Here is an illustration with the mean and median of the length of the sepal for the &lt;code&gt;iris&lt;/code&gt; dataset integrated in a sentence:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Screenshot%202020-02-17%20at%2023.10.07.png&#34; alt=&#34;Example of inline code and text&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Example of inline code and text&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;This combination of text and code will give the following output in the generated report:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The mean of the length of the sepal is 5.8433333 and the standard deviation is 0.8280661.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This technique, referred as &lt;em&gt;inline code&lt;/em&gt;, allows you to insert results directly into the text of a R Markdown document. And as mentioned, if the dataset changes, the results incorporated inside the text (the mean and standard deviation in our case) will automatically be adjusted to the new dataset, exactly like the output of a code chunk is dynamically updated if the dataset changes.&lt;/p&gt;
&lt;p&gt;This technique of inline code and the fact that it is possible to combine code, outputs of code, and text to comment the outputs makes R Markdown my favorite tool when it comes to statistical analyses. Since I discovered the power of R Markdown (and I am still learning as it has a huge amount of possibilities and features), I almost never write R code in scripts anymore. Every R code I write is supplemented by text and inline code in a R Markdown document, resulting in a professional and complete final document ready to be shared, published, or stored for future usage. If you are unfamiliar to this type of document, I invite you to learn more about it and to try it with your next analysis, you will most likely not go back to R scripts anymore.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;highlight-text-like-it-is-code&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Highlight text like it is code&lt;/h3&gt;
&lt;p&gt;Alternatively to the inline code technique, you may want to make some text appears as if it is a piece of code in the generated report, without actually running it.&lt;/p&gt;
&lt;p&gt;For this, surround your text with back ticks (the same backward apostrophe used for inline code) without the letter &lt;code&gt;r&lt;/code&gt;. Writing the following:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Screenshot%202020-03-15%20at%2011.30.04.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;will produce this in the generated report:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;For example, in this sentence I would like to highlight the variable name &lt;code&gt;Species&lt;/code&gt; from the dataframe &lt;code&gt;iris&lt;/code&gt; as if it is a piece of code.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The word “Species” and “iris” appear and are highlighted as if it is a piece of code.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;images&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Images&lt;/h2&gt;
&lt;p&gt;In addition to code, results and text, you can also insert images in your final document. To insert an image, place it in your current working directory, and outside a code chunk write:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;![](path_to_your_image.jpg)&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Note that the the file/url path is NOT quoted. To add an alt text to your image, add it between the square brackets &lt;code&gt;[]&lt;/code&gt;:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;![alt text here](path_to_your_image.jpg)&lt;/code&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;tables&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Tables&lt;/h2&gt;
&lt;p&gt;There are two options to insert tables in R Markdown documents:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;the &lt;code&gt;kable()&lt;/code&gt; function from the &lt;code&gt;{knitr}&lt;/code&gt; package&lt;/li&gt;
&lt;li&gt;the &lt;code&gt;pander()&lt;/code&gt; function from the &lt;code&gt;{pander}&lt;/code&gt; package&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Here are an example of a table without any formatting, and the same code with the two functions applied on the &lt;code&gt;iris&lt;/code&gt; dataset:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# without formatting
summary(iris)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100  
##  1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300  
##  Median :5.800   Median :3.000   Median :4.350   Median :1.300  
##  Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199  
##  3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800  
##  Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500  
##        Species  
##  setosa    :50  
##  versicolor:50  
##  virginica :50  
##                 
##                 
## &lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# with kable()
library(knitr)
kable(summary(iris))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Screenshot%202020-02-18%20at%2015.27.34.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# with pander()
library(pander)
pander(summary(iris))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/getting-started-in-r-markdown_files/Screenshot%202020-02-18%20at%2015.27.41.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The advantage of &lt;code&gt;pander()&lt;/code&gt; over &lt;code&gt;kable()&lt;/code&gt; is that it can be used for many more different outputs than table. Try on your own code, with results of a &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;linear regression&lt;/a&gt; or a simple vector for example.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;additional-notes-and-useful-resources&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Additional notes and useful resources&lt;/h1&gt;
&lt;p&gt;For more advanced users, R Markdown files can also be used to create &lt;a href=&#34;https://statsandr.com/tags/shiny/&#34;&gt;Shiny apps&lt;/a&gt;, websites (this website is built thanks to R Markdown and the &lt;code&gt;{blogdown}&lt;/code&gt; package), to write scientific papers based on templates from several international journals (with the &lt;code&gt;{rticles}&lt;/code&gt; package), or even to write books (with the &lt;code&gt;{bookdown}&lt;/code&gt; package).&lt;/p&gt;
&lt;p&gt;To continue learning about R Markdown, see two complete cheat sheets from the R Studio team &lt;a href=&#34;https://rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdf&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt; and &lt;a href=&#34;https://rstudio.com/wp-content/uploads/2015/03/rmarkdown-reference.pdf&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;, and a more complete guide &lt;a href=&#34;https://bookdown.org/yihui/rmarkdown/&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt; written by Yihui Xie, J. J. Allaire and Garrett Grolemund.&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 convinced you to use R Markdown for your future projects. 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 Markdown&lt;/a&gt; to increase even further your efficiency in R Markdown.&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>Do my data follow a normal distribution? A note on the most widely used distribution and how to test for normality in R</title>
      <link>https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/</link>
      <pubDate>Wed, 29 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#what-is-a-normal-distribution&#34; id=&#34;toc-what-is-a-normal-distribution&#34;&gt;What is a normal distribution?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#empirical-rule&#34; id=&#34;toc-empirical-rule&#34;&gt;Empirical rule&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#parameters&#34; id=&#34;toc-parameters&#34;&gt;Parameters&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#probabilities-and-standard-normal-distribution&#34; id=&#34;toc-probabilities-and-standard-normal-distribution&#34;&gt;Probabilities and standard normal distribution&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#areas-under-the-normal-distribution-in-r-and-by-hand&#34; id=&#34;toc-areas-under-the-normal-distribution-in-r-and-by-hand&#34;&gt;Areas under the normal distribution in R and by hand&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#ex.-1&#34; id=&#34;toc-ex.-1&#34;&gt;Ex. 1&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#in-r&#34; id=&#34;toc-in-r&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand&#34; id=&#34;toc-by-hand&#34;&gt;By hand&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#ex.-2&#34; id=&#34;toc-ex.-2&#34;&gt;Ex. 2&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#in-r-1&#34; id=&#34;toc-in-r-1&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand-1&#34; id=&#34;toc-by-hand-1&#34;&gt;By hand&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#ex.-3&#34; id=&#34;toc-ex.-3&#34;&gt;Ex. 3&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#in-r-2&#34; id=&#34;toc-in-r-2&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand-2&#34; id=&#34;toc-by-hand-2&#34;&gt;By hand&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#ex.-4&#34; id=&#34;toc-ex.-4&#34;&gt;Ex. 4&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#in-r-3&#34; id=&#34;toc-in-r-3&#34;&gt;In R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#by-hand-3&#34; id=&#34;toc-by-hand-3&#34;&gt;By hand&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#ex.-5&#34; id=&#34;toc-ex.-5&#34;&gt;Ex. 5&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#why-is-the-normal-distribution-so-crucial-in-statistics&#34; id=&#34;toc-why-is-the-normal-distribution-so-crucial-in-statistics&#34;&gt;Why is the normal distribution so crucial in statistics?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#how-to-test-the-normality-assumption&#34; id=&#34;toc-how-to-test-the-normality-assumption&#34;&gt;How to test the normality assumption&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#histogram&#34; id=&#34;toc-histogram&#34;&gt;Histogram&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#density-plot&#34; id=&#34;toc-density-plot&#34;&gt;Density plot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#qq-plot&#34; id=&#34;toc-qq-plot&#34;&gt;QQ-plot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#normality-test&#34; id=&#34;toc-normality-test&#34;&gt;Normality test&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#references&#34; id=&#34;toc-references&#34;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/Do-my-data-follow-a-normal-distribution.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;what-is-a-normal-distribution&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;What is a normal distribution?&lt;/h1&gt;
&lt;p&gt;The normal distribution is a function that defines how a set of measurements is distributed around the center of these measurements (i.e., the mean). Many natural phenomena in real life can be approximated by a bell-shaped frequency distribution known as the normal distribution or the Gaussian distribution.&lt;/p&gt;
&lt;p&gt;The normal distribution is a mount-shaped, unimodal and symmetric distribution where most measurements gather around the mean. Moreover, the further a measure deviates from the mean, the lower the probability of occurring. In this sense, for a given variable, it is common to find values close to the mean, but less and less likely to find values as we move away from the mean. Last but not least, since the normal distribution is symmetric around its mean, extreme values in both tails of the distribution are equivalently unlikely. For instance, given that adult height follows a normal distribution, most adults are close to the average height and extremely short adults occur as infrequently as extremely tall adults.&lt;/p&gt;
&lt;p&gt;In this article, the focus is on understanding the normal distribution, the associated empirical rule, its parameters and how to compute &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-scores to find probabilities under the curve (illustrated with examples). As it is a requirement in some &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt; and &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt;, we also show 4 complementary methods to test the normality assumption in R.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;empirical-rule&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Empirical rule&lt;/h1&gt;
&lt;p&gt;Data possessing an approximately normal distribution have a definite variation, as expressed by the following empirical rule:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\mu \pm \sigma\)&lt;/span&gt; includes approximately 68% of the observations&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\mu \pm 2 \cdot \sigma\)&lt;/span&gt; includes approximately 95% of the observations&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(\mu \pm 3 \cdot \sigma\)&lt;/span&gt; includes almost all of the observations (99.7% to be more precise)&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/empirical-rule-normal-distribution.png&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Normal distribution &amp;amp; empirical rule (68-95-99.7% rule)&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\sigma\)&lt;/span&gt; correspond to the population mean and population standard deviation, respectively.&lt;/p&gt;
&lt;p&gt;The empirical rule, also known as the 68-95-99.7% rule, is illustrated by the following 2 examples.&lt;/p&gt;
&lt;p&gt;Suppose that the scores of an exam in statistics given to all students in a Belgian university are known to have, approximately, a normal distribution with mean &lt;span class=&#34;math inline&#34;&gt;\(\mu = 67\)&lt;/span&gt; and standard deviation &lt;span class=&#34;math inline&#34;&gt;\(\sigma = 9\)&lt;/span&gt;. It can then be deduced that approximately 68% of the scores are between 58 and 76, that approximately 95% of the scores are between 49 and 85, and that almost all of the scores (99.7%) are between 40 and 94. Thus, knowing the mean and the standard deviation gives us a fairly good picture of the distribution of scores.&lt;/p&gt;
&lt;p&gt;Now suppose that a single university student is randomly selected from those who took the exam. What is the probability that her score will be between 49 and 85? Based on the empirical rule, we find that 0.95 is a reasonable answer to this probability question.&lt;/p&gt;
&lt;p&gt;The utility and value of the empirical rule are due to the common occurrence of approximately normal distributions of measurements in nature. For example, IQ, shoe size, height, birth weight, etc. are approximately normally-distributed. You will find that approximately 95% of these measurements will be within &lt;span class=&#34;math inline&#34;&gt;\(2\sigma\)&lt;/span&gt; of their mean &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-wackerly2014mathematical&#34; role=&#34;doc-biblioref&#34;&gt;Wackerly, Mendenhall, and Scheaffer 2014&lt;/a&gt;)&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;parameters&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Parameters&lt;/h1&gt;
&lt;p&gt;Like many probability distributions, the shape and probabilities of the normal distribution is defined entirely by some parameters. The normal distribution has two parameters:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#mean&#34;&gt;mean &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt;&lt;/a&gt;, and&lt;/li&gt;
&lt;li&gt;the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#variance&#34;&gt;variance &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2\)&lt;/span&gt;&lt;/a&gt; (i.e., the square of the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#standard-deviation&#34;&gt;standard deviation &lt;span class=&#34;math inline&#34;&gt;\(\sigma\)&lt;/span&gt;&lt;/a&gt;).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The mean &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; locates the center of the distribution, that is, the central tendency of the observations, and the variance &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2\)&lt;/span&gt; defines the width of the distribution, that is, the spread of the observations.&lt;/p&gt;
&lt;p&gt;The mean &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; can take on any finite value (i.e., &lt;span class=&#34;math inline&#34;&gt;\(-\infty &amp;lt; \mu &amp;lt; \infty\)&lt;/span&gt;), whereas the variance &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2\)&lt;/span&gt; can assume any positive finite value (i.e., &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2 &amp;gt; 0\)&lt;/span&gt;). The shape of the normal distribution changes based on these two parameters. Since there is an infinite number of combinations of the mean and variance, there is an infinite number of normal distributions, and thus an infinite number of forms.&lt;/p&gt;
&lt;p&gt;For instance, see how the shapes of the normal distributions vary when the two parameters change:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-1-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-1-2.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;As you can see on the second graph, when the variance (or the standard deviation) decreases, the observations are closer to the mean. On the contrary, when the variance (or standard deviation) increases, it is more likely that observations will be further away from the mean.&lt;/p&gt;
&lt;p&gt;A random variable &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; which follows a normal distribution with a mean of 430 and a variance of 17 is denoted &lt;span class=&#34;math inline&#34;&gt;\(X ~ \sim \mathcal{N}(\mu = 430, \sigma^2 = 17)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;We have seen that, although different normal distributions have different shapes, all normal distributions have common characteristics:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;They are symmetric, 50% of the population is above the mean and 50% of the population is below the mean&lt;/li&gt;
&lt;li&gt;The mean, median and mode are equal&lt;/li&gt;
&lt;li&gt;The empirical rule detailed earlier is applicable to all normal distributions&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;probabilities-and-standard-normal-distribution&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Probabilities and standard normal distribution&lt;/h1&gt;
&lt;p&gt;Probabilities and quantiles for random variables with normal distributions are easily found using R via the functions &lt;code&gt;pnorm()&lt;/code&gt; and &lt;code&gt;qnorm()&lt;/code&gt;. Probabilities associated with a normal distribution can also be found using this &lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-101/&#34; target=&#34;_blank&#34; rel=&#34;noopener&#34;&gt;Shiny app&lt;/a&gt;. However, before computing probabilities, we need to learn more about the standard normal distribution and the &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score.&lt;/p&gt;
&lt;p&gt;Although there are infinitely many normal distributions (since there is a normal distribution for every combination of mean and variance), we need only one table to find the probabilities under the normal curve: the &lt;strong&gt;standard normal distribution&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The normal standard distribution is a special case of the normal distribution where the mean is equal to 0 and the variance is equal to 1. A normal random variable &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; can always be transformed to a standard normal random variable &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;, a process known as “scaling” or “standardization”, by subtracting the mean from the observation, and dividing the result by the standard deviation. Formally:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[Z = \frac{x - \mu}{\sigma}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt; is the observation, &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\sigma\)&lt;/span&gt; the mean and standard deviation of the population from which the observation was drawn. So the mean of the standard normal distribution is 0, and its variance is 1, denoted &lt;span class=&#34;math inline&#34;&gt;\(Z ~ \sim \mathcal{N}(\mu = 0, \sigma^2 = 1)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;From this formula, we see that &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;, referred as standard score or &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score, allows to see how far away one specific observation is from the mean of all observations, with the distance expressed in standard deviations. In other words, the &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score corresponds to the number of standard deviations an observation is away from the mean. A positive &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score means that the specific observation is above the mean, whereas a negative &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score means that the specific observation is below the mean. &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-scores are often used to compare an individual to her peers, or more generally, a measurement compared to its distribution.&lt;/p&gt;
&lt;p&gt;For instance, suppose a student scoring 60 at a statistics exam with the mean score of the class being 40, and scoring 65 at an economics exam with the mean score of the class being 80. Given the “raw” scores, one would say that the student performed better in economics than in statistics. However, taking into consideration her peers, it is clear that the student performed &lt;em&gt;relatively&lt;/em&gt; better in statistics than in economics.&lt;/p&gt;
&lt;p&gt;Computing &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-scores allows to take into consideration all other students (i.e., the entire distribution) and gives a better measure of comparison. Let’s compute the &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-scores for the two exams, assuming that the score for both exams follow a normal distribution with the following parameters:&lt;/p&gt;
&lt;center&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Statistics&lt;/th&gt;
&lt;th&gt;Economics&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Mean&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;40&lt;/td&gt;
&lt;td&gt;80&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Standard deviation&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;8&lt;/td&gt;
&lt;td&gt;12.5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Student’s score&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;60&lt;/td&gt;
&lt;td&gt;65&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-scores for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Statistics: &lt;span class=&#34;math inline&#34;&gt;\(z_{stat} = \frac{60 - 40}{8} = 2.5\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Economics: &lt;span class=&#34;math inline&#34;&gt;\(z_{econ} = \frac{65 - 80}{12.5} = -1.2\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;On the one hand, the &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score for the exam in statistics is positive (&lt;span class=&#34;math inline&#34;&gt;\(z_{stat} = 2.5\)&lt;/span&gt;) which means that she performed better than average. On the other hand, her score for the exam in economics is negative (&lt;span class=&#34;math inline&#34;&gt;\(z_{econ} = -1.2\)&lt;/span&gt;) which means that she performed worse than average. Below an illustration of her grades in a standard normal distribution for better comparison:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-2-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Although the score in economics is better in absolute terms, the score in statistics is actually relatively better when comparing each score within its own distribution.&lt;/p&gt;
&lt;p&gt;Furthermore, &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score also enables to compare observations that would otherwise be impossible because they have different units for example. Suppose you want to compare a salary in € with a weight in kg. Without standardization, there is no way to conclude whether someone is more extreme in terms of her wage or in terms of her weight. Thanks to &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-scores, we can compare two values that were in the first place not comparable to each other.&lt;/p&gt;
&lt;p&gt;Final remark regarding the interpretation of a &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score: a rule of thumb is that an observation with a &lt;span class=&#34;math inline&#34;&gt;\(z\)&lt;/span&gt;-score between -3 and -2 or between 2 and 3 is considered as a rare value. An observation with a &lt;span class=&#34;math inline&#34;&gt;\(z\)&lt;/span&gt;-score smaller than -3 or larger than 3 is considered as an extremely rare value. A value with any other &lt;span class=&#34;math inline&#34;&gt;\(z\)&lt;/span&gt;-score is considered as not rare nor extremely rare.&lt;/p&gt;
&lt;div id=&#34;areas-under-the-normal-distribution-in-r-and-by-hand&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Areas under the normal distribution in R and by hand&lt;/h2&gt;
&lt;p&gt;Now that we have covered the &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;-score, we are going to use it to determine the area under the curve of a normal distribution.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note that there are several ways to arrive at the solution in the following exercises. You may therefore use other steps than the ones presented to obtain the same result.&lt;/em&gt;&lt;/p&gt;
&lt;div id=&#34;ex.-1&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Ex. 1&lt;/h3&gt;
&lt;p&gt;Let &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt; denote a normal random variable with mean 0 and standard deviation 1, find &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;We actually look for the shaded area in the following figure:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/Screenshot%202020-01-30%20at%2014.18.54.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Standard normal distribution: &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1)\)&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;In R&lt;/h4&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;pnorm(1,
  mean = 0,
  sd = 1, # sd stands for standard deviation
  lower.tail = FALSE
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.1586553&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We look for the probability of &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt; being larger than 1 so we set the argument &lt;code&gt;lower.tail = FALSE&lt;/code&gt;. The default &lt;code&gt;lower.tail = TRUE&lt;/code&gt; would give the result for &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;lt; 1)\)&lt;/span&gt;. Note that &lt;span class=&#34;math inline&#34;&gt;\(P(Z = 1) = 0\)&lt;/span&gt; so writing &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1)\)&lt;/span&gt; or &lt;span class=&#34;math inline&#34;&gt;\(P(Z \ge 1)\)&lt;/span&gt; is equivalent.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;by-hand&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;By hand&lt;/h4&gt;
&lt;p&gt;See that the random variable &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt; has already a mean of 0 and a standard deviation of 1, so no transformation is required. To find the probabilities by hand, we need to refer to the standard normal distribution table shown below:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/Screenshot%202020-01-30%20at%2015.07.44.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Standard normal distribution table &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-wackerly2014mathematical&#34; role=&#34;doc-biblioref&#34;&gt;Wackerly, Mendenhall, and Scheaffer 2014&lt;/a&gt;)&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;From the illustration at the top of the table, we see that the values inside the table correspond to the area under the normal curve &lt;strong&gt;above&lt;/strong&gt; a certain &lt;span class=&#34;math inline&#34;&gt;\(z\)&lt;/span&gt;. Since we are looking precisely at the probability above &lt;span class=&#34;math inline&#34;&gt;\(z = 1\)&lt;/span&gt; (since we look for &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1)\)&lt;/span&gt;), we can simply proceed down the first (&lt;span class=&#34;math inline&#34;&gt;\(z\)&lt;/span&gt;) column in the table until &lt;span class=&#34;math inline&#34;&gt;\(z = 1.0\)&lt;/span&gt;. The probability is 0.1587. Thus, &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1) = 0.1587\)&lt;/span&gt;. This is similar to what we found using R, except that values in the table are rounded to 4 digits.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;ex.-2&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Ex. 2&lt;/h3&gt;
&lt;p&gt;Let &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt; denote a normal random variable with mean 0 and standard deviation 1, find &lt;span class=&#34;math inline&#34;&gt;\(P(−1 \le Z \le 1)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;We are looking for the shaded area in the following figure:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/Screenshot%202020-01-30%20at%2014.19.14.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Standard normal distribution: &lt;span class=&#34;math inline&#34;&gt;\(P(−1 \le Z \le 1)\)&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r-1&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;In R&lt;/h4&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;pnorm(1, lower.tail = TRUE) - pnorm(-1, lower.tail = TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.6826895&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the arguments by default for the mean and the standard deviation are &lt;code&gt;mean = 0&lt;/code&gt; and &lt;code&gt;sd = 1&lt;/code&gt;. Since this is what we need, we can omit them.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;by-hand-1&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;By hand&lt;/h4&gt;
&lt;p&gt;For this exercise we proceed by steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;The shaded area corresponds to the entire area under the normal curve minus the two white areas in both tails of the curve.&lt;/li&gt;
&lt;li&gt;We know that the normal distribution is symmetric.&lt;/li&gt;
&lt;li&gt;Therefore, the shaded area is the entire area under the curve minus two times the white area in the right tail of the curve, the white area in the right tail of the curve being &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1)\)&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;We also know that the entire area under the normal curve is 1.&lt;/li&gt;
&lt;li&gt;Thus, the shaded area is 1 minus 2 times &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1)\)&lt;/span&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(−1 \le Z \le 1) = 1 - 2 \cdot P(Z &amp;gt; 1)\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[= 1 - 2 \cdot 0.1587 = 0.6826\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1) = 0.1587\)&lt;/span&gt; has been found in the previous exercise.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;ex.-3&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Ex. 3&lt;/h3&gt;
&lt;p&gt;Let &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt; denote a normal random variable with mean 0 and standard deviation 1, find &lt;span class=&#34;math inline&#34;&gt;\(P(0 \le Z \le 1.37)\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;We are looking for the shaded area in the following figure:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/Screenshot%202020-01-30%20at%2014.19.46.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Standard normal distribution: &lt;span class=&#34;math inline&#34;&gt;\(P(0 \le Z \le 1.37)\)&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r-2&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;In R&lt;/h4&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;pnorm(0, lower.tail = FALSE) - pnorm(1.37, lower.tail = FALSE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.4146565&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;by-hand-2&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;By hand&lt;/h4&gt;
&lt;p&gt;Again we proceed by steps for this exercise:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;We know that &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 0) = 0.5\)&lt;/span&gt; since the entire area under the curve is 1, half of it is 0.5.&lt;/li&gt;
&lt;li&gt;The shaded area is half of the entire area under the curve minus the area from 1.37 to infinity.&lt;/li&gt;
&lt;li&gt;The area under the curve from 1.37 to infinity corresponds to &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1.37)\)&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;Therefore, the shaded area is &lt;span class=&#34;math inline&#34;&gt;\(0.5 - P(Z &amp;gt; 1.37)\)&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;To find &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1.37)\)&lt;/span&gt;, proceed down the &lt;span class=&#34;math inline&#34;&gt;\(z\)&lt;/span&gt; column in the table to the entry 1.3 and then across the top of the table to the column labeled .07 to read &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1.37) = .0853\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Thus,&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(0 \le Z \le 1.37) = P(Z &amp;gt; 0) - P(Z &amp;gt; 1.37)\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[ = 0.5 - 0.0853 = 0.4147\]&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;ex.-4&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Ex. 4&lt;/h3&gt;
&lt;p&gt;Recap the example presented in the empirical rule: Suppose that the scores of an exam in statistics given to all students in a Belgian university are known to have a normal distribution with mean &lt;span class=&#34;math inline&#34;&gt;\(\mu = 67\)&lt;/span&gt; and standard deviation &lt;span class=&#34;math inline&#34;&gt;\(\sigma = 9\)&lt;/span&gt;. What fraction of the scores lies between 70 and 80?&lt;/p&gt;
&lt;p&gt;We are looking for the shaded area in the following figure:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/Screenshot%202020-01-30%20at%2016.24.30.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(P(70 \le X \le 80)\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(X \sim \mathcal{N}(\mu = 67, \sigma^2 = 9^2)\)&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;in-r-3&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;In R&lt;/h4&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;pnorm(70, mean = 67, sd = 9, lower.tail = FALSE) - pnorm(80, mean = 67, sd = 9, lower.tail = FALSE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.2951343&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;by-hand-3&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;By hand&lt;/h4&gt;
&lt;p&gt;Remind that we are looking for &lt;span class=&#34;math inline&#34;&gt;\(P(70 \le X \le 80)\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(X \sim \mathcal{N}(\mu = 67, \sigma^2 = 9^2)\)&lt;/span&gt;. The random variable &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; is in its “raw” format, meaning that it has not been standardized yet since the mean is 67 and the variance is &lt;span class=&#34;math inline&#34;&gt;\(9^2\)&lt;/span&gt;. We thus need to first apply the transformation to standardize the endpoints 70 and 80 with the following formula:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[Z = \frac{X - \mu}{\sigma}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;After the standardization, &lt;span class=&#34;math inline&#34;&gt;\(x = 70\)&lt;/span&gt; becomes (in terms of &lt;span class=&#34;math inline&#34;&gt;\(z\)&lt;/span&gt;, so in terms of deviation from the mean expressed in standard deviation):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[z = \frac{70 - 67}{9} = 0.3333\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;and &lt;span class=&#34;math inline&#34;&gt;\(x = 80\)&lt;/span&gt; becomes:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[z = \frac{80 - 67}{9} = 1.4444\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The figure above in terms of &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; is now in terms of &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt;:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/Screenshot%202020-01-30%20at%2016.37.13.png&#34; style=&#34;width:100.0%&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(P(0.3333 \le Z \le 1.4444)\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(Z \sim \mathcal{N}(\mu = 0, \sigma^2 = 1)\)&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;Finding the probability &lt;span class=&#34;math inline&#34;&gt;\(P(0.3333 \le Z \le 1.4444)\)&lt;/span&gt; is similar to exercises 1 to 3:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;The shaded area corresponds to the area under the curve from &lt;span class=&#34;math inline&#34;&gt;\(z = 0.3333\)&lt;/span&gt; to &lt;span class=&#34;math inline&#34;&gt;\(z = 1.4444\)&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;In other words, the shaded area is the area under the curve from &lt;span class=&#34;math inline&#34;&gt;\(z = 0.3333\)&lt;/span&gt; to infinity minus the area under the curve from &lt;span class=&#34;math inline&#34;&gt;\(z = 1.4444\)&lt;/span&gt; to infinity.&lt;/li&gt;
&lt;li&gt;From the table, &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 0.3333) = 0.3707\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(P(Z &amp;gt; 1.4444) = 0.0749\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Thus:&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[P(0.3333 \le Z \le 1.4444)\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[= P(Z &amp;gt; 0.3333) - P(Z &amp;gt; 1.4444)\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[= 0.3707 - 0.0749 = 0.2958\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The difference with the probability found using in R comes from the rounding.&lt;/p&gt;
&lt;p&gt;To conclude this exercise, we can say that, given that the mean scores is 67 and the standard deviation is 9, 29.58% of the students scored between 70 and 80.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;ex.-5&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Ex. 5&lt;/h3&gt;
&lt;p&gt;See another example in a context &lt;a href=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/#example&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;why-is-the-normal-distribution-so-crucial-in-statistics&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Why is the normal distribution so crucial in statistics?&lt;/h1&gt;
&lt;p&gt;The normal distribution is important for three main reasons:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Some statistical &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis tests&lt;/a&gt; assume that the data follow a normal distribution&lt;/li&gt;
&lt;li&gt;The central limit theorem states that, for a large number of observations (usually &lt;span class=&#34;math inline&#34;&gt;\(n &amp;gt; 30\)&lt;/span&gt;), no matter what is the underlying distribution of the original variable, the distribution of the sample means (&lt;span class=&#34;math inline&#34;&gt;\(\overline{X}_n\)&lt;/span&gt;) and of the sum (&lt;span class=&#34;math inline&#34;&gt;\(S_n = \sum_{i = 1}^n X_i\)&lt;/span&gt;) may be approached by a normal distribution &lt;span class=&#34;citation&#34;&gt;(&lt;a href=&#34;#ref-stevens2013intermediate&#34; role=&#34;doc-biblioref&#34;&gt;Stevens 2013&lt;/a&gt;)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Linear and nonlinear &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;regression&lt;/a&gt; assume that the residuals are normally-distributed (for small sample sizes)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;It is therefore useful to know how to test for normality in R, which is the topic of next sections.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;how-to-test-the-normality-assumption&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How to test the normality assumption&lt;/h1&gt;
&lt;p&gt;As mentioned above, some &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt; require that the data follow a normal distribution, or the result of the test may be flawed.&lt;/p&gt;
&lt;p&gt;In this section, we show 4 complementary methods to determine whether your data follow a normal distribution in R.&lt;/p&gt;
&lt;div id=&#34;histogram&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Histogram&lt;/h2&gt;
&lt;p&gt;A &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#histogram&#34;&gt;histogram&lt;/a&gt; displays the spread and shape of a distribution, so it is a good starting point to evaluate normality.&lt;/p&gt;
&lt;p&gt;Let’s have a look at the histogram of a distribution that we would expect to follow a normal distribution, the height of 1,000 adults in cm:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-7-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The normal curve with the corresponding mean and variance has been added to the histogram. The histogram follows the normal curve so the data seems to follow a normal distribution.&lt;/p&gt;
&lt;p&gt;Below the minimal code for a histogram in R with the dataset &lt;code&gt;iris&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;data(iris)
hist(iris$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-8-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In &lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;&lt;code&gt;{ggplot2}&lt;/code&gt;&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(iris) +
  aes(x = Sepal.Length) +
  geom_histogram()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-9-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Histograms are however not sufficient, particularly in the case of small samples because the number of bins greatly change its appearance. Histograms are not recommended when the number of observations is less than 20 because it does not always correctly illustrate the distribution. See two examples below with datasets of 10 and 12 observations:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-10-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-10-2.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Can you tell whether these datasets follow a normal distribution? Surprisingly, both series are generated from a normal distribution!&lt;/p&gt;
&lt;p&gt;In the remaining of the article, we will use the dataset of the 12 adults. If you would like to follow my code in your own script, here is how I generated the data:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(42)
dat_hist &amp;lt;- data.frame(
  value = rnorm(12, mean = 165, sd = 5)
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;rnorm()&lt;/code&gt; function generates random numbers from a normal distribution (12 random numbers with a mean of 165 and standard deviation of 5 in this case). These 12 observations are then saved in the dataset called &lt;code&gt;dat_hist&lt;/code&gt; under the variable &lt;code&gt;value&lt;/code&gt;. Note that &lt;code&gt;set.seed(42)&lt;/code&gt; is important to obtain the exact same data as me.&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;density-plot&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Density plot&lt;/h2&gt;
&lt;p&gt;&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#density-plot&#34;&gt;Density plots&lt;/a&gt; also provide a visual judgment about whether the data follow a normal distribution.&lt;/p&gt;
&lt;p&gt;They are similar to histograms as they also allow to analyze the spread and the shape of the distribution. However, they are a smoothed version of the histogram.&lt;/p&gt;
&lt;p&gt;Here is the density plot drawn from the dataset on the height of the 12 adults discussed above:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(density(dat_hist$value))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-12-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggpubr}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggpubr) # package must be installed first
ggdensity(dat_hist$value,
  main = &amp;quot;Density plot of adult height&amp;quot;,
  xlab = &amp;quot;Height (cm)&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-13-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Since it is hard to test for normality from histograms and density plots only, it is recommended to corroborate these graphs with a QQ-plot. QQ-plot, also known as normality plot, is the third method presented to evaluate normality.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;qq-plot&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;QQ-plot&lt;/h2&gt;
&lt;p&gt;Like histograms and density plots, &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#qq-plot&#34;&gt;QQ-plots&lt;/a&gt; allow to visually evaluate the normality assumption.&lt;/p&gt;
&lt;p&gt;Here is the QQ-plot drawn from the dataset on the height of the 12 adults discussed above:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(car)
qqPlot(dat_hist$value)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-14-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## [1] 12  2&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In &lt;code&gt;{ggpubr}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggpubr)
ggqqplot(dat_hist$value)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-15-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Instead of looking at the spread of the data (as it is the case with histograms and density plots), with QQ-plots we only need to ascertain whether the data points follow the line (sometimes referred as Henry’s line).&lt;/p&gt;
&lt;p&gt;If points are close to the reference line and within the confidence bands, the normality assumption can be considered as met. The bigger the deviation between the points and the reference line and the more they lie outside the confidence bands, the less likely that the normality condition is met. The height of these 12 adults seem to follow a normal distribution because points follow the line and all of them lie within the confidence bands.&lt;/p&gt;
&lt;p&gt;When facing a non-normal distribution as shown by the QQ-plot below (systematic departure from the reference line), the first step is usually to apply the logarithm transformation on the data and recheck to see whether the log-transformed data are normally distributed.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r_files/figure-html/unnamed-chunk-16-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;If this is the case, the data are said to follow a &lt;em&gt;log-normal&lt;/em&gt; distribution. Applying the logarithm transformation can be done in R with the &lt;code&gt;log()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;Note that QQ-plots are also a convenient way to assess whether residuals from &lt;a href=&#34;https://statsandr.com/blog/multiple-linear-regression-made-simple/&#34;&gt;linear regression&lt;/a&gt; follow a normal distribution.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;normality-test&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Normality test&lt;/h2&gt;
&lt;p&gt;The 3 tools presented above were a visual inspection of the normality. Nonetheless, visual inspection may sometimes be unreliable so it is also possible to formally test whether the data follow a normal distribution with statistical tests.&lt;/p&gt;
&lt;p&gt;These normality tests compare the distribution of the data to a normal distribution in order to assess whether observations show an important deviation from normality.&lt;/p&gt;
&lt;p&gt;The two most common normality tests are Shapiro-Wilk’s test and Kolmogorov-Smirnov test. Both tests have the same hypotheses, that is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_0\)&lt;/span&gt;: the data follow a normal distribution&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(H_1\)&lt;/span&gt;: the data do not follow a normal distribution&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Shapiro-Wilk test is recommended for normality test as it provides better power than Kolmogorov-Smirnov test.&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt; In R, the Shapiro-Wilk test of normality can be done with the function &lt;code&gt;shapiro.test()&lt;/code&gt;:&lt;a href=&#34;#fn4&#34; class=&#34;footnote-ref&#34; id=&#34;fnref4&#34;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;shapiro.test(dat_hist$value)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Shapiro-Wilk normality test
## 
## data:  dat_hist$value
## W = 0.93968, p-value = 0.4939&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From the output, we see that the &lt;span class=&#34;math inline&#34;&gt;\(p\)&lt;/span&gt;-value &lt;span class=&#34;math inline&#34;&gt;\(&amp;gt; 0.05\)&lt;/span&gt; implying that we do not reject the null hypothesis that the data follow a normal distribution. This test goes in the same direction than the QQ-plot, which showed no significant deviation from the normality (as all points lied within the confidence bands).&lt;/p&gt;
&lt;p&gt;It is important to note that, in practice, normality tests are often considered as too conservative in the sense that for large sample size (&lt;span class=&#34;math inline&#34;&gt;\(n &amp;gt; 50\)&lt;/span&gt;), a small deviation from the normality may cause the normality condition to be violated.&lt;/p&gt;
&lt;p&gt;A normality test is a &lt;a href=&#34;https://statsandr.com/blog/hypothesis-test-by-hand/&#34;&gt;hypothesis test&lt;/a&gt;, so as the sample size increases, their capacity of detecting smaller differences increases. So as the number of observations increases, the Shapiro-Wilk test becomes very sensitive even to a small deviation from normality. As a consequence, it happens that according to the normality test the data do not follow a normal distribution although the departures from the normal distribution is negligible so the data could in fact be considered to follow approximately a normal distribution. For this reason, it is often the case that the normality condition is verified based on a combination of all methods presented in this article, that is, visual inspections (with histograms and QQ-plots) and a formal inspection (with the Shapiro-Wilk test for instance).&lt;/p&gt;
&lt;p&gt;I personally tend to prefer QQ-plots over histograms and normality tests so I do not have to bother about the sample size. This article showed the different methods that are available, your choice will of course depends on the type of your data and the context of your analyses.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope the article helped you to learn more about the normal distribution and how to test for normality in R.&lt;/p&gt;
&lt;p&gt;As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;references&#34; class=&#34;section level1 unnumbered&#34;&gt;
&lt;h1&gt;References&lt;/h1&gt;
&lt;div id=&#34;refs&#34; class=&#34;references csl-bib-body hanging-indent&#34;&gt;
&lt;div id=&#34;ref-stevens2013intermediate&#34; class=&#34;csl-entry&#34;&gt;
Stevens, James P. 2013. &lt;em&gt;Intermediate Statistics: A Modern Approach&lt;/em&gt;. Routledge.
&lt;/div&gt;
&lt;div id=&#34;ref-wackerly2014mathematical&#34; class=&#34;csl-entry&#34;&gt;
Wackerly, Dennis, William Mendenhall, and Richard L Scheaffer. 2014. &lt;em&gt;Mathematical Statistics with Applications&lt;/em&gt;. Cengage Learning.
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;The argument &lt;code&gt;lower.tail = TRUE&lt;/code&gt; is also the default so we could omit it as well. However, for clarity and to make sure I compute the propabilities in the correct side of the curve, I used to keep this argument explicit by writing it.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;The &lt;code&gt;set.seed()&lt;/code&gt; function accepts any numeric as argument. Generating random numbers (via &lt;code&gt;rnorm()&lt;/code&gt; for instance) implies that R will generates different random numbers every time you generate these random numbers (so every time you run the function &lt;code&gt;rnorm()&lt;/code&gt;). To make sure R generates the exact same numbers every time you run the function, a seed can be set with the function &lt;code&gt;set.seed()&lt;/code&gt;. Setting a seed implies that R will generate random numbers, but these numbers will always be the same as long as the seed is the same. This allows to replicate results that are based on a random generation. Change the seed if you want to generate other random values.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;The Shapiro-Wilk test is based on the correlation between the sample and the corresponding normal scores.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn4&#34;&gt;&lt;p&gt;In R, the Kolmogorov-Smirnov test is performed with the function &lt;code&gt;ks.test()&lt;/code&gt;.&lt;a href=&#34;#fnref4&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>RStudio addins, or how to make your coding life easier?</title>
      <link>https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/</link>
      <pubDate>Sun, 26 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#what-are-rstudio-addins&#34; id=&#34;toc-what-are-rstudio-addins&#34;&gt;What are RStudio addins?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#installation&#34; id=&#34;toc-installation&#34;&gt;Installation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#addins&#34; id=&#34;toc-addins&#34;&gt;Addins&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#esquisse&#34; id=&#34;toc-esquisse&#34;&gt;Esquisse&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#ggthemeassist&#34; id=&#34;toc-ggthemeassist&#34;&gt;ggThemeAssist&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#questionr&#34; id=&#34;toc-questionr&#34;&gt;Questionr&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#recoding-factors&#34; id=&#34;toc-recoding-factors&#34;&gt;Recoding factors&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#reordering-factors&#34; id=&#34;toc-reordering-factors&#34;&gt;Reordering factors&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#categorize-a-numeric-variable&#34; id=&#34;toc-categorize-a-numeric-variable&#34;&gt;Categorize a numeric variable&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#remedy&#34; id=&#34;toc-remedy&#34;&gt;Remedy&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#styler&#34; id=&#34;toc-styler&#34;&gt;Styler&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#snakecaser&#34; id=&#34;toc-snakecaser&#34;&gt;Snakecaser&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#viewpipesteps&#34; id=&#34;toc-viewpipesteps&#34;&gt;ViewPipeSteps&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#ymlthis&#34; id=&#34;toc-ymlthis&#34;&gt;Ymlthis&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#reprex&#34; id=&#34;toc-reprex&#34;&gt;Reprex&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#blogdown&#34; id=&#34;toc-blogdown&#34;&gt;Blogdown&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/rstudio-addins.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;what-are-rstudio-addins&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;What are RStudio addins?&lt;/h1&gt;
&lt;p&gt;Although I have been using RStudio for several years, I only recently discovered RStudio addins. Since then, I am using these addins almost every time I use RStudio.&lt;/p&gt;
&lt;p&gt;What are RStudio addins? RStudio addins are extensions which provide a simple mechanism for executing advanced R functions from within RStudio. In simpler words, when executing an addin (by clicking a button in the Addins menu), the corresponding code is executed without you having to write the code. If it is still not clear, remember that for &lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/&#34;&gt;importing a dataset in RStudio&lt;/a&gt;, you have two options:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;import it by writing the code (thanks to the &lt;code&gt;read.csv()&lt;/code&gt; function for instance)&lt;/li&gt;
&lt;li&gt;or you can import it by clicking on the “Import Dataset” button in the Environment pane, set the importing settings, then click on “Import”&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;An RStudio addin is exactly like the Import Dataset button but for other common functionalities. So you could write code as you can import a dataset by writing code, but thanks to RStudio addins you can execute code without actually writing the necessary code. By using the RStudio addins, RStudio will run the required code for you. RStudio addins can be as simple as a function that inserts a commonly used snippet of code, and as complex as a Shiny application that accepts input from the user to draw a plot. RStudio addins have the advantage that they allow you to execute complex and advanced code much more easily than if you would have to write it yourself.&lt;/p&gt;
&lt;p&gt;I believe addins are worth trying for all R users. Beginners will have the possibility to use functions that they would not have used otherwise because the code is too complex, whereas advanced users may find them useful to speed up the writing of their code in some circumstances. For other tips in R, see the article “&lt;a href=&#34;https://statsandr.com/blog/tips-and-tricks-in-rstudio-and-r-markdown/&#34;&gt;Tips and tricks in RStudio and R Markdown&lt;/a&gt;”.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;installation&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Installation&lt;/h1&gt;
&lt;p&gt;RStudio Addins are distributed as R packages. So before being able to use them, you need to install them.&lt;/p&gt;
&lt;p&gt;You can install an addin exactly the same way you &lt;a href=&#34;https://statsandr.com/blog/an-efficient-way-to-install-and-load-r-packages/&#34;&gt;install a package&lt;/a&gt;: &lt;code&gt;install.packages(&#34;name_of_addin&#34;)&lt;/code&gt;. Once you have installed the R package that contains the addin, it will immediately become available within RStudio, via the Addins menu located at the top.&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/rstudio-addins-toolbar.png&#34; alt=&#34;RStudio addins toolbar&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;RStudio addins toolbar&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;See this &lt;a href=&#34;https://rstudio.github.io/rstudioaddins/#registering-addins&#34; target=&#34;_blank&#34;&gt;guide&lt;/a&gt; if you want to install a personal package as addin. In short, you have to create an R package, put your functions in a specific file and RStudio will automatically discover and register these addins when your package is installed.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;addins&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Addins&lt;/h1&gt;
&lt;p&gt;If you are still not convinced, see below a list of the addins I find most useful together with concrete examples in the following sections.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#esquisse&#34;&gt;Esquisse&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#questionr&#34;&gt;Questionr&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#remedy&#34;&gt;Remedy&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#styler&#34;&gt;Styler&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#snakecaser&#34;&gt;Snakecaser&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#viewpipesteps&#34;&gt;ViewPipeSteps&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#ymlthis&#34;&gt;Ymlthis&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#reprex&#34;&gt;Reprex&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/#blogdown&#34;&gt;Blogdown&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that this list is not exhaustive and you are likely to find others useful too depending on what type of analyses you do on RStudio. Feel free to comment at the end of the article to let me know (and other readers) addins you found worth using.&lt;/p&gt;
&lt;div id=&#34;esquisse&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Esquisse&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;{esquisse}&lt;/code&gt; is an addin developed by a French company called &lt;a href=&#34;https://www.dreamrs.fr/&#34; target=&#34;_blank&#34;&gt;dreamRs&lt;/a&gt;. Here is how they define it:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;This addin allows you to interactively explore your data by visualizing it with the ggplot2 package. It allows you to draw bar plots, curves, scatter plots, histograms, boxplot and sf objects, then export the graph or retrieve the code to reproduce the graph.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;With this addin you can easily create beautiful graphs from 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; and the best part according to me is that you can retrieve the code to reproduce the graph. Compared to the default &lt;code&gt;{graphics}&lt;/code&gt; package, it is true that graphs from the &lt;code&gt;{ggplot2}&lt;/code&gt; package look usually better but the code is also longer and more complex. With this addin, you can draw graphs from the &lt;code&gt;{ggplot2}&lt;/code&gt; package by dragging and dropping variables of interest in an user-friendly and interactive window, and then use the generated code in your script.&lt;/p&gt;
&lt;p&gt;For the sake of illustration, let’s say we want to create a scatter plot of the variables &lt;code&gt;Sepal.Length&lt;/code&gt; and &lt;code&gt;Petal.Length&lt;/code&gt; of the dataset &lt;code&gt;iris&lt;/code&gt; and color the points by the variable &lt;code&gt;Species&lt;/code&gt;. For this, follow these steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;load the dataset and rename it:&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;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- iris&lt;/code&gt;&lt;/pre&gt;
&lt;ol start=&#34;2&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;install the package &lt;code&gt;{esquisse}&lt;/code&gt;. This must be done only once&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;install.packages(&amp;quot;esquisse&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;ol start=&#34;3&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;open the ‘ggplot2’ builder from the RStudio Addins menu:&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/esquisse-RStudio-addin.png&#34; alt=&#34;Step 3: Open ‘ggplot2’ builder from the RStudio addins menu&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 3: Open ‘ggplot2’ builder from the RStudio addins menu&lt;/div&gt;
&lt;/div&gt;
&lt;ol start=&#34;4&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Select the dataset you want to work on (in this case &lt;code&gt;dat&lt;/code&gt;) and click on “Validate imported data” after checking that the number of observations and variables are correct (green box):&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/esquisse-rstudio-addin2.png&#34; alt=&#34;Step 4: Select dataset and validate the imported data&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 4: Select dataset and validate the imported data&lt;/div&gt;
&lt;/div&gt;
&lt;ol start=&#34;5&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Drag and drop the variables of interest in the corresponding areas. In this case, we would like to draw a scatter plot of the variables &lt;code&gt;Sepal.Length&lt;/code&gt; and &lt;code&gt;Petal.Length&lt;/code&gt; and color points based on the variable &lt;code&gt;Species&lt;/code&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/esquisse-rstudio-addin3.png&#34; alt=&#34;Step 5: Drag and drop the variables in the corresponding areas&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 5: Drag and drop the variables in the corresponding areas&lt;/div&gt;
&lt;/div&gt;
&lt;ol start=&#34;6&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Click on “&amp;lt;/&amp;gt; Export &amp;amp; code” at the bottom right of the window. You can either copy the code and paste it where you want to place it in your script, or you can click on “Insert code in script” to place the code where your cursor is located in your script:&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/esquisse-rstudio-addin4.png&#34; alt=&#34;Step 6: Retrieve the code to use it in your script&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 6: Retrieve the code to use it in your script&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;If you chose the second option, the following code should appear where your cursor was located:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Sepal.Length, y = Petal.Length, colour = Species) +
  geom_point(shape = &amp;quot;circle&amp;quot;, size = 1.5) +
  scale_color_hue(direction = 1) +
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_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;Many different options and customizations are possible (e.g., axis labels, colors, legend position, theme, data filtering, etc.). For this, use the buttons located at the bottom of the window (“Labels &amp;amp; title”, “Plot options” and “Data”). You can see the changes instantly in the window, and when the plot corresponds to your needs, export the code into your script.&lt;/p&gt;
&lt;p&gt;I will not go into more details regarding the different types of plots and the customizations, but make sure to try other types of plots by moving variables and customize it to see what is possible.&lt;/p&gt;
&lt;div id=&#34;ggthemeassist&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;ggThemeAssist&lt;/h3&gt;
&lt;p&gt;Note that there is another addin called &lt;code&gt;{ggThemeAssist}&lt;/code&gt; which helps you to edit the &lt;code&gt;theme()&lt;/code&gt; layer of a &lt;code&gt;{ggplot2}&lt;/code&gt; plot.&lt;/p&gt;
&lt;p&gt;This layer allows you to modify the appearance of the background, grids, axes, labels, legend, (sub)title, caption, etc.&lt;/p&gt;
&lt;p&gt;To use this addin:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Write the code of the plot in &lt;code&gt;{ggplot2}&lt;/code&gt; (it does not work for a plot written in base R)&lt;/li&gt;
&lt;li&gt;Highlight the code&lt;/li&gt;
&lt;li&gt;Select the &lt;code&gt;{ggThemeAssist}&lt;/code&gt; addin in the addins menu&lt;/li&gt;
&lt;li&gt;Customize your plot according to your needs&lt;/li&gt;
&lt;li&gt;Click on the button Done and your code will be edited with your changes:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Sepal.Length, y = Petal.Length, colour = Species) +
  geom_point(shape = &amp;quot;circle&amp;quot;, size = 1.5) +
  scale_color_hue(direction = 1) +
  theme_minimal() +
  theme(
    panel.grid.major = element_line(linetype = &amp;quot;blank&amp;quot;),
    panel.grid.minor = element_line(linetype = &amp;quot;blank&amp;quot;),
    legend.position = c(0.88, 0.22)
  ) +
  theme(plot.caption = element_text(face = &amp;quot;italic&amp;quot;)) +
  labs(
    title = &amp;quot;Sepal &amp;amp; petal length by species&amp;quot;,
    x = &amp;quot;Sepal length&amp;quot;, y = &amp;quot;Petal length&amp;quot;,
    caption = &amp;quot;Data: iris&amp;quot;
  )&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_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;Find more information about the &lt;code&gt;theme()&lt;/code&gt; layer in this &lt;a href=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/ggplot_theme_system_cheatsheet.pdf&#34;&gt;cheatsheet&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;questionr&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Questionr&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;{questionr}&lt;/code&gt; addin is useful for survey analysis and when dealing with &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#factor&#34;&gt;factor variables&lt;/a&gt;. With this addin, you can easily reorder and recode factor variables. The addin also allows to easily transform a numeric variable into factors (i.e., categorize a continuous variable) thanks to the &lt;code&gt;cut()&lt;/code&gt; function. Like any other addin, after having installed the &lt;code&gt;{questionr}&lt;/code&gt; package, you should see it appearing in the addins menu at the top. From the addins dropdown menu, choose whether you want to reorder or recode your factor variable, or categorize your numeric variable.&lt;/p&gt;
&lt;div id=&#34;recoding-factors&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Recoding factors&lt;/h3&gt;
&lt;p&gt;Instead of writing the &lt;code&gt;recode()&lt;/code&gt; function from the &lt;code&gt;{dplyr}&lt;/code&gt; package, we can use the &lt;code&gt;{questionr}&lt;/code&gt; addin.&lt;/p&gt;
&lt;p&gt;For this example, let’s say we want to recode the &lt;code&gt;Species&lt;/code&gt; variable to shorten the length of the factors, and then store this new variable as &lt;code&gt;Species_rec&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/Screenshot%202020-01-27%20at%2010.04.35.png&#34; alt=&#34;Step 1: Select the variable to be recoded and the recoding settings&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 1: Select the variable to be recoded and the recoding settings&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/Screenshot%202020-01-27%20at%2010.04.39.png&#34; alt=&#34;Step 2: Specify the names of the new factors&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 2: Specify the names of the new factors&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/Screenshot%202020-01-27%20at%2010.04.42.png&#34; alt=&#34;Step 3: Check the results thanks to the contingency table and use the code at the top&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 3: Check the results thanks to the contingency table and use the code at the top&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;reordering-factors&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Reordering factors&lt;/h3&gt;
&lt;p&gt;Similar to recoding, we can reorder factors thanks to the &lt;code&gt;{questionr}&lt;/code&gt; addin. Let’s say we want to reorder the 3 factors of the &lt;code&gt;Species&lt;/code&gt; variable such that the order is &lt;code&gt;versicolor&lt;/code&gt; then &lt;code&gt;virginica&lt;/code&gt; and finally &lt;code&gt;setosa&lt;/code&gt;. This can be done as follows:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/Screenshot%202020-01-27%20at%2010.06.28.png&#34; alt=&#34;Step 1: Select the variable to reorder and the new variable name&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 1: Select the variable to reorder and the new variable name&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/Screenshot%202020-01-27%20at%2010.06.31.png&#34; alt=&#34;Step 2: Specify the order you want&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 2: Specify the order you want&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/Screenshot%202020-01-27%20at%2010.06.36.png&#34; alt=&#34;Step 3: Use the code at the top in your script&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 3: Use the code at the top in your script&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;categorize-a-numeric-variable&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Categorize a numeric variable&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;{questionr}&lt;/code&gt; addin also allows to transform a numeric variable into a categorical variable. This is often done for the age, when age is transformed into age groups for instance. For this example, let’s say we want to create 3 categories of the variable &lt;code&gt;Sepal.Length&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/Screenshot%202020-01-27%20at%2010.39.12.png&#34; alt=&#34;Step 1: Choose the variable to be transformed and the new variable name&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 1: Choose the variable to be transformed and the new variable name&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/Screenshot%202020-01-27%20at%2010.39.41.png&#34; alt=&#34;Step 2: Set the number of breaks equal to 3&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 2: Set the number of breaks equal to 3&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;(Try by yourself the other cutting methods and see the results directly in the window.)&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/Screenshot%202020-01-27%20at%2010.40.15.png&#34; alt=&#34;Step 3: Check the result thanks to the barplot at the bottom&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 3: Check the result thanks to the barplot at the bottom&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/Screenshot%202020-01-27%20at%2010.40.23.png&#34; alt=&#34;Step 4: Use the code in your script&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 4: Use the code in your script&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;remedy&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Remedy&lt;/h2&gt;
&lt;p&gt;If you often write in R Markdown, the &lt;code&gt;{remedy}&lt;/code&gt; addins will greatly facilitate your work. The addins allow you to add bold, creating lists, urls, italics, title (H1 to H6), footnote, etc. in an efficient way. I reckon that some of these tasks can be done faster by using the code directly rather than by going through the addins menu and then selecting the transformations you want. However, I personally cannot remember the code for all transformations, and it is quicker to apply it through the menu than by searching for the answer on Google or on your Markdown cheat sheet.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;styler&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Styler&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;{styler}&lt;/code&gt; addin allows to reformat your code in a more readable format by running &lt;code&gt;styler::tidyverse_style()&lt;/code&gt;. It works both for R scripts and R Markdown documents. You can either reformat the selected code, the active file or the active package. I find this addin particularly useful before sharing or publishing my code, so that it respects the most common styling guidelines for code.&lt;/p&gt;
&lt;p&gt;For instance, a piece of code like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;1+1
#this is a comment
  for(i in 1:10){if(!i%%2){next}
print(i)
 }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;becomes much more neat and readable:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;1 + 1
# this is a comment
for (i in 1:10) {
  if (!i %% 2) {
    next
  }
  print(i)
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;snakecaser&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Snakecaser&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;{snakecaser}&lt;/code&gt; addins converts a character string to the snake case styling. Snake case styling is the practice of writing character strings of several words separated by space into character strings with words separated with an underscore (&lt;code&gt;_&lt;/code&gt;). Moreover, it replaces capital letters with lowercases. For instance, the following string:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;This is the Test 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;will be transformed to:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;this_is_the_test_1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The snake case styling is particularly useful (and even recommended by many R users) for variables, functions and file names, etc.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;viewpipesteps&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;ViewPipeSteps&lt;/h2&gt;
&lt;p&gt;Thanks to a reader of this article, I discovered the &lt;code&gt;ViewPipeSteps&lt;/code&gt; addin. This addin allows to print or view the output of your pipe chain after each step.&lt;/p&gt;
&lt;p&gt;For instance, here is a chain with the dataset &lt;code&gt;diamonds&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(tidyverse)

diamonds %&amp;gt;%
  select(carat, cut, color, clarity, price) %&amp;gt;%
  group_by(color) %&amp;gt;%
  summarise(n = n(), price = mean(price)) %&amp;gt;%
  arrange(desc(color))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 7 × 3
##   color     n price
##   &amp;lt;ord&amp;gt; &amp;lt;int&amp;gt; &amp;lt;dbl&amp;gt;
## 1 J      2808 5324.
## 2 I      5422 5092.
## 3 H      8304 4487.
## 4 G     11292 3999.
## 5 F      9542 3725.
## 6 E      9797 3077.
## 7 D      6775 3170.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you are unsure about your pipe chain or want to debug it, you can view the output after each step by highlighting your entire chain then clicking on “View Pipe Chain Steps” from the addins menu:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/Screenshot%202020-03-11%20at%2018.06.01.png&#34; /&gt;&lt;/p&gt;
&lt;p&gt;From the addins menu, you can choose to either print the result to the console, or view the result in a new pane (as if you called the function &lt;code&gt;View()&lt;/code&gt; after each step of the pipe). Clicking on View Pipe Chain Steps will open a new window with the output of each step:&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/Screenshot%202020-03-11%20at%2018.09.59.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Note that you have to use the following command to install the &lt;code&gt;ViewPipeSteps&lt;/code&gt; addin:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;devtools::install_github(&amp;quot;daranzolin/ViewPipeSteps&amp;quot;)
library(ViewPipeSteps)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, you have no more excuses to use this pipe operator!&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;ymlthis&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Ymlthis&lt;/h2&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/ymlthis%20addin%20to%20write%20YAML%20header%20for%20R%20Markdown%20documents.png&#34; style=&#34;width:100.0%&#34; alt=&#34;ymlthis addin to easily write YAML header&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;ymlthis addin to easily write YAML header&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;The &lt;a href=&#34;https://ymlthis.r-lib.org/index.html&#34; target=&#34;_blank&#34;&gt;&lt;code&gt;ymlthis&lt;/code&gt; addin&lt;/a&gt; makes it easy to write YAML front matter for R Markdown and related documents. The addin will create YAML for you and put it in a file, such as an &lt;code&gt;.Rmd&lt;/code&gt; file, or on your clipboard.&lt;/p&gt;
&lt;p&gt;This addin is particularly useful if you want to write (more complicated) &lt;a href=&#34;https://statsandr.com/blog/getting-started-in-r-markdown/#yaml-header&#34;&gt;YAML header&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;reprex&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Reprex&lt;/h2&gt;
&lt;p&gt;If you often ask the R community for help, this addin may be very useful!&lt;/p&gt;
&lt;p&gt;It is important to remember that when you ask someone for help, you have to help them help you by giving a precise and clear overview of your problem. This helps the community to quickly understand your issue and thus reduces the response time.&lt;/p&gt;
&lt;p&gt;In most cases, this involves providing a reproducible example, that is to say a piece of code (as small and as readable as possible) reproducing the problem encountered.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;{reprex}&lt;/code&gt; addin allows you to transform your reproducible example so that it can easily be shared on platforms such as GitHub, Stack Overflow, RStudio community, etc. The layout of your reproducible example will be adapted to the platform, and you can even include information about your R session.&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;Here is how to use it steps by steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;First create your reproducible example in R (remember to keep it as short and readable as possible to save time to potential helpers):&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/rstudio-addin-reprex-reproducible-example1.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Minimal reproducible example&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Minimal reproducible example&lt;/div&gt;
&lt;/div&gt;
&lt;ol start=&#34;2&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Select the &lt;code&gt;{reprex}&lt;/code&gt; addin in the list of addins:&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/rstudio-addin-reprex-reproducible-example2.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Select the {reprex} addin&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Select the {reprex} addin&lt;/div&gt;
&lt;/div&gt;
&lt;ol start=&#34;3&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Select the platform on which you will post your issue (and check “Append session info” if you want to display your session info at the end of your reproducible example):&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/rstudio-addin-reprex-reproducible-example3.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Set options in the {reprex} addin&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Set options in the {reprex} addin&lt;/div&gt;
&lt;/div&gt;
&lt;ol start=&#34;4&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;You can now see the output of your reproducible example (right panel), but more importantly, it has been copied in your clipboard and it is now ready to be pasted on the platform of your choice:&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/rstudio-addin-reprex-reproducible-example4.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Your reprex is copied in your clipboard&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Your reprex is copied in your clipboard&lt;/div&gt;
&lt;/div&gt;
&lt;ol start=&#34;5&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Paste your reprex on the platform of your choice (here, it is posted as an issue on GitHub):&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/rstudio-addin-reprex-reproducible-example5.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Paste your reprex&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Paste your reprex&lt;/div&gt;
&lt;/div&gt;
&lt;ol start=&#34;6&#34; style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Check the final result of your reproducible example:&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/best-rstudio-addins-in-rstudio-or-how-to-make-your-coding-life-easier_files/rstudio-addin-reprex-reproducible-example6.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Final result&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Final result&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;(Visit this GitHub &lt;a href=&#34;https://github.com/AntoineSoetewey/statsandr/issues/12&#34; target=&#34;_blank&#34;&gt;issue&lt;/a&gt; to see the final result.)&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;blogdown&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Blogdown&lt;/h2&gt;
&lt;p&gt;I put this addin at the end of the list because it will be of interest for only a limited number of RStudio users: people maintaining a blog written in R like this one (see why I recommend everyone to &lt;a href=&#34;https://statsandr.com/blog/7-benefits-of-sharing-your-code-in-a-data-science-blog/&#34;&gt;start a technical blog&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;The most useful functionalities in this addin are the following:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;New post: create a new post with &lt;code&gt;blogdown::new_post()&lt;/code&gt;. It can be used to create new pages as well, not only posts&lt;/li&gt;
&lt;li&gt;Insert image: insert an external image into a blog post&lt;/li&gt;
&lt;li&gt;Update metadata: update the title, author, date, categories and tags of the current blog post&lt;/li&gt;
&lt;li&gt;Serve site: run &lt;code&gt;blogdown::serve_site()&lt;/code&gt; to live preview your website locally&lt;/li&gt;
&lt;/ul&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 that you will find these addins useful for your future R-related projects. See other &lt;a href=&#34;https://statsandr.com/blog/tips-and-tricks-in-rstudio-and-r-markdown/&#34;&gt;tips and tricks in RStudio and R Markdown&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 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;You actually do not need to rename it. However, I often rename the datasets I work on with the same generic name &lt;code&gt;dat&lt;/code&gt; so when I reuse codes from a previous project for a new project, I do not have to change the name of the dataset in the code.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Thanks to Josep for the &lt;a href=&#34;https://medium.com/@josepmporra/great-post-you-could-have-a-look-to-reprex-addins-to-build-reproducible-examples-26bcdc0f8ed4&#34; target=&#34;_blank&#34;&gt;suggestion&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>Descriptive statistics in R</title>
      <link>https://statsandr.com/blog/descriptive-statistics-in-r/</link>
      <pubDate>Wed, 22 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/descriptive-statistics-in-r/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#data&#34; id=&#34;toc-data&#34;&gt;Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#minimum-and-maximum&#34; id=&#34;toc-minimum-and-maximum&#34;&gt;Minimum and maximum&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#range&#34; id=&#34;toc-range&#34;&gt;Range&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#mean&#34; id=&#34;toc-mean&#34;&gt;Mean&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#median&#34; id=&#34;toc-median&#34;&gt;Median&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#first-and-third-quartile&#34; id=&#34;toc-first-and-third-quartile&#34;&gt;First and third quartile&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#other-quantiles&#34; id=&#34;toc-other-quantiles&#34;&gt;Other quantiles&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#interquartile-range&#34; id=&#34;toc-interquartile-range&#34;&gt;Interquartile range&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#standard-deviation-and-variance&#34; id=&#34;toc-standard-deviation-and-variance&#34;&gt;Standard deviation and variance&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#summary&#34; id=&#34;toc-summary&#34;&gt;Summary&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#coefficient-of-variation&#34; id=&#34;toc-coefficient-of-variation&#34;&gt;Coefficient of variation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#mode&#34; id=&#34;toc-mode&#34;&gt;Mode&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#correlation&#34; id=&#34;toc-correlation&#34;&gt;Correlation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#contingency-table&#34; id=&#34;toc-contingency-table&#34;&gt;Contingency table&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#mosaic-plot&#34; id=&#34;toc-mosaic-plot&#34;&gt;Mosaic plot&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#barplot&#34; id=&#34;toc-barplot&#34;&gt;Barplot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#histogram&#34; id=&#34;toc-histogram&#34;&gt;Histogram&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#boxplot&#34; id=&#34;toc-boxplot&#34;&gt;Boxplot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#dotplot&#34; id=&#34;toc-dotplot&#34;&gt;Dotplot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scatterplot&#34; id=&#34;toc-scatterplot&#34;&gt;Scatterplot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#line-plot&#34; id=&#34;toc-line-plot&#34;&gt;Line plot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#qq-plot&#34; id=&#34;toc-qq-plot&#34;&gt;QQ-plot&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#for-a-single-variable&#34; id=&#34;toc-for-a-single-variable&#34;&gt;For a single variable&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#by-groups&#34; id=&#34;toc-by-groups&#34;&gt;By groups&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#density-plot&#34; id=&#34;toc-density-plot&#34;&gt;Density plot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#correlation-plot&#34; id=&#34;toc-correlation-plot&#34;&gt;Correlation plot&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#advanced-descriptive-statistics&#34; id=&#34;toc-advanced-descriptive-statistics&#34;&gt;Advanced descriptive statistics&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#summarytools-package&#34; id=&#34;toc-summarytools-package&#34;&gt;&lt;code&gt;{summarytools}&lt;/code&gt; package&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#frequency-tables-with-freq&#34; id=&#34;toc-frequency-tables-with-freq&#34;&gt;Frequency tables with &lt;code&gt;freq()&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#cross-tabulations-with-ctable&#34; id=&#34;toc-cross-tabulations-with-ctable&#34;&gt;Cross-tabulations with &lt;code&gt;ctable()&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#descriptive-statistics-with-descr&#34; id=&#34;toc-descriptive-statistics-with-descr&#34;&gt;Descriptive statistics with &lt;code&gt;descr()&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#data-frame-summaries-with-dfsummary&#34; id=&#34;toc-data-frame-summaries-with-dfsummary&#34;&gt;Data frame summaries with &lt;code&gt;dfSummary()&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#describeby-from-the-psych-package&#34; id=&#34;toc-describeby-from-the-psych-package&#34;&gt;&lt;code&gt;describeBy()&lt;/code&gt; from the &lt;code&gt;{psych}&lt;/code&gt; package&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#aggregate-function&#34; id=&#34;toc-aggregate-function&#34;&gt;&lt;code&gt;aggregate()&lt;/code&gt; function&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#summaryby-from-doby&#34; id=&#34;toc-summaryby-from-doby&#34;&gt;&lt;code&gt;summaryBy()&lt;/code&gt; from &lt;code&gt;{doBy}&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#group_by-and-summarise-from-dplyr&#34; id=&#34;toc-group_by-and-summarise-from-dplyr&#34;&gt;&lt;code&gt;group_by()&lt;/code&gt; and &lt;code&gt;summarise()&lt;/code&gt; from &lt;code&gt;{dplyr}&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/descriptive-statistics-in-r.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;This article explains how to compute the main descriptive statistics in R and how to present them graphically. To learn more about the reasoning behind each descriptive statistics, how to compute them by hand and how to interpret them, read the article “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;Descriptive statistics by hand&lt;/a&gt;”.&lt;/p&gt;
&lt;p&gt;To briefly recap what have been said in that article, descriptive statistics (in the broad sense of the term) is a branch of statistics aiming at summarizing, describing and presenting a series of values or a dataset. Descriptive statistics is often the first step and an important part in any statistical analysis. It allows to check the quality of the data and it helps to “understand” the data by having a clear overview of it. If well presented, descriptive statistics is already a good starting point for further analyses. There exists many measures to summarize a dataset. They are divided into two types:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;location measures and&lt;/li&gt;
&lt;li&gt;dispersion measures&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Location measures give an understanding about the central tendency of the data, whereas dispersion measures give an understanding about the spread of the data. In this article, we focus only on the implementation in R of the most common descriptive statistics and their visualizations (when deemed appropriate). See online or in the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;above mentioned article&lt;/a&gt; for more information about the purpose and usage of each measure.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;data&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Data&lt;/h1&gt;
&lt;p&gt;We use the dataset &lt;code&gt;iris&lt;/code&gt; throughout the article. This dataset is imported by default in R, you only need to load it by running &lt;code&gt;iris&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- iris # load the iris dataset and renamed it dat&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Below a preview of this dataset and its structure:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;head(dat) # first 6 observations&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;str(dat) # structure of dataset&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## &amp;#39;data.frame&amp;#39;:	150 obs. of  5 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  $ Species     : Factor w/ 3 levels &amp;quot;setosa&amp;quot;,&amp;quot;versicolor&amp;quot;,..: 1 1 1 1 1 1 1 1 1 1 ...&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The dataset contains 150 observations and 5 variables, representing the length and width of the sepal and petal and the species of 150 flowers. Length and width of the sepal and petal are numeric variables and the species is a factor with 3 levels (indicated by &lt;code&gt;num&lt;/code&gt; and &lt;code&gt;Factor w/ 3 levels&lt;/code&gt; after the name of the variables). See the &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/&#34;&gt;different variables types in R&lt;/a&gt; if you need a refresh.&lt;/p&gt;
&lt;p&gt;Regarding plots, we present the default graphs and the graphs from the well-known &lt;code&gt;{ggplot2}&lt;/code&gt; package. Graphs from the &lt;code&gt;{ggplot2}&lt;/code&gt; package usually have a better look but it requires more advanced coding skills (see the article “&lt;a href=&#34;https://statsandr.com/blog/graphics-in-r-with-ggplot2/&#34;&gt;Graphics in R with ggplot2&lt;/a&gt;” to learn more). If you need to publish or share your graphs, I suggest using &lt;code&gt;{ggplot2}&lt;/code&gt; if you can, otherwise the default graphics will do the job.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Tip:&lt;/em&gt; I recently discovered the ggplot2 builder from the &lt;code&gt;{esquisse}&lt;/code&gt; addins. See how you can easily &lt;a href=&#34;https://statsandr.com/blog/rstudio-addins-or-how-to-make-your-coding-life-easier/&#34;&gt;draw graphs from the &lt;code&gt;{ggplot2}&lt;/code&gt; package&lt;/a&gt; without having to code it yourself.&lt;/p&gt;
&lt;p&gt;All plots displayed in this article can be customized. For instance, it is possible to edit the title, x and y-axis labels, color, etc. However, customizing plots is beyond the scope of this article so all plots are presented without any customization. Interested readers will find numerous resources online.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;minimum-and-maximum&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Minimum and maximum&lt;/h1&gt;
&lt;p&gt;Minimum and maximum can be found thanks to the &lt;code&gt;min()&lt;/code&gt; and &lt;code&gt;max()&lt;/code&gt; functions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;min(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 4.3&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;max(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 7.9&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Alternatively the &lt;code&gt;range()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rng &amp;lt;- range(dat$Sepal.Length)
rng&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 4.3 7.9&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;gives you the minimum and maximum directly. Note that the output of the &lt;code&gt;range()&lt;/code&gt; function is actually an object containing the minimum and maximum (in that order). This means you can actually access the minimum with:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rng[1] # rng = name of the object specified above&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 4.3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and the maximum with:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rng[2]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 7.9&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This reminds us that, in R, there are often several ways to arrive at the same result. The method that uses the shortest piece of code is usually preferred as a shorter piece of code is less prone to coding errors and more readable.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;range&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Range&lt;/h1&gt;
&lt;p&gt;The range can then be easily computed, as you have guessed, by subtracting the minimum from the maximum:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;max(dat$Sepal.Length) - min(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 3.6&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To my knowledge, there is no default function to compute the range. However, if you are familiar with writing functions in R
&lt;!-- (if not, see this article on [how to write a function in R](/blog/xxx/)) --&gt;
, you can create your own function to compute the range:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;range2 &amp;lt;- function(x) {
  range &amp;lt;- max(x) - min(x)
  return(range)
}

range2(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 3.6&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;which is equivalent than &lt;span class=&#34;math inline&#34;&gt;\(max - min\)&lt;/span&gt; presented above.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;mean&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Mean&lt;/h1&gt;
&lt;p&gt;The mean can be computed with the &lt;code&gt;mean()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mean(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 5.843333&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Tips:&lt;/em&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;if there is at least one missing value in your dataset, use &lt;code&gt;mean(dat$Sepal.Length, na.rm = TRUE)&lt;/code&gt; to compute the mean with the NA excluded. This argument can be used for most functions presented in this article, not only the mean&lt;/li&gt;
&lt;li&gt;for a truncated mean, use &lt;code&gt;mean(dat$Sepal.Length, trim = 0.10)&lt;/code&gt; and change the &lt;code&gt;trim&lt;/code&gt; argument to your needs&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;median&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Median&lt;/h1&gt;
&lt;p&gt;The median can be computed thanks to the &lt;code&gt;median()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;median(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 5.8&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or with the &lt;code&gt;quantile()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;quantile(dat$Sepal.Length, 0.5)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 50% 
## 5.8&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;since the quantile of order 0.5 (&lt;span class=&#34;math inline&#34;&gt;\(q_{0.5}\)&lt;/span&gt;) corresponds to the median.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;first-and-third-quartile&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;First and third quartile&lt;/h1&gt;
&lt;p&gt;As the median, the first and third quartiles can be computed thanks to the &lt;code&gt;quantile()&lt;/code&gt; function and by setting the second argument to 0.25 or 0.75:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;quantile(dat$Sepal.Length, 0.25) # first quartile&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 25% 
## 5.1&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;quantile(dat$Sepal.Length, 0.75) # third quartile&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 75% 
## 6.4&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You may have seen that the results above are slightly different than the results you would have found if you compute the first and third quartiles &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;by hand&lt;/a&gt;. It is normal, there are many methods to compute them (R actually has 7 methods to compute the quantiles!). However, the methods presented here and in the article “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics by hand&lt;/a&gt;” are the easiest and most “standard” ones. Furthermore, results do not dramatically change between the two methods.&lt;/p&gt;
&lt;div id=&#34;other-quantiles&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Other quantiles&lt;/h2&gt;
&lt;p&gt;As you have guessed, any quantile can also be computed with the &lt;code&gt;quantile()&lt;/code&gt; function. For instance, the &lt;span class=&#34;math inline&#34;&gt;\(4^{th}\)&lt;/span&gt; decile or the &lt;span class=&#34;math inline&#34;&gt;\(98^{th}\)&lt;/span&gt; percentile:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;quantile(dat$Sepal.Length, 0.4) # 4th decile&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 40% 
## 5.6&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;quantile(dat$Sepal.Length, 0.98) # 98th percentile&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 98% 
## 7.7&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;interquartile-range&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Interquartile range&lt;/h1&gt;
&lt;p&gt;The interquartile range (i.e., the difference between the first and third quartile) can be computed with the &lt;code&gt;IQR()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;IQR(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1.3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or alternatively with the &lt;code&gt;quantile()&lt;/code&gt; function again:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;quantile(dat$Sepal.Length, 0.75) - quantile(dat$Sepal.Length, 0.25)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 75% 
## 1.3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As mentioned earlier, when possible it is usually recommended to use the shortest piece of code to arrive at the result. For this reason, the &lt;code&gt;IQR()&lt;/code&gt; function is preferred to compute the interquartile range.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;standard-deviation-and-variance&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Standard deviation and variance&lt;/h1&gt;
&lt;p&gt;The standard deviation and the variance is computed with the &lt;code&gt;sd()&lt;/code&gt; and &lt;code&gt;var()&lt;/code&gt; functions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sd(dat$Sepal.Length) # standard deviation&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.8280661&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;var(dat$Sepal.Length) # variance&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.6856935&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Remember from the article &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics by hand&lt;/a&gt; that the standard deviation and the variance are different whether we compute it for a sample or a population (see the &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;difference between sample and population&lt;/a&gt;). In R, the standard deviation and the variance are computed as if the data represent a sample (so the denominator is &lt;span class=&#34;math inline&#34;&gt;\(n - 1\)&lt;/span&gt;, where &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is the number of observations). To my knowledge, there is no function by default in R that computes the standard deviation or variance for a population.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Tip:&lt;/em&gt; to compute the standard deviation (or variance) of multiple variables at the same time, use &lt;code&gt;lapply()&lt;/code&gt; with the appropriate statistics as second argument:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;lapply(dat[, 1:4], sd)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $Sepal.Length
## [1] 0.8280661
## 
## $Sepal.Width
## [1] 0.4358663
## 
## $Petal.Length
## [1] 1.765298
## 
## $Petal.Width
## [1] 0.7622377&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The command &lt;code&gt;dat[, 1:4]&lt;/code&gt; selects the variables 1 to 4 as the fifth variable is a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;qualitative variable&lt;/a&gt; and the standard deviation cannot be computed on such type of variable. See a recap of the different &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/&#34;&gt;data types in R&lt;/a&gt; if needed.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;summary&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;You can compute the minimum, &lt;span class=&#34;math inline&#34;&gt;\(1^{st}\)&lt;/span&gt; quartile, median, mean, &lt;span class=&#34;math inline&#34;&gt;\(3^{rd}\)&lt;/span&gt; quartile and the maximum for all numeric variables of a dataset at once using &lt;code&gt;summary()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100  
##  1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300  
##  Median :5.800   Median :3.000   Median :4.350   Median :1.300  
##  Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199  
##  3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800  
##  Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500  
##        Species  
##  setosa    :50  
##  versicolor:50  
##  virginica :50  
##                 
##                 
## &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Tip:&lt;/em&gt; if you need these descriptive statistics by group use the &lt;code&gt;by()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;by(dat, dat$Species, summary)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## dat$Species: setosa
##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.300   Min.   :2.300   Min.   :1.000   Min.   :0.100  
##  1st Qu.:4.800   1st Qu.:3.200   1st Qu.:1.400   1st Qu.:0.200  
##  Median :5.000   Median :3.400   Median :1.500   Median :0.200  
##  Mean   :5.006   Mean   :3.428   Mean   :1.462   Mean   :0.246  
##  3rd Qu.:5.200   3rd Qu.:3.675   3rd Qu.:1.575   3rd Qu.:0.300  
##  Max.   :5.800   Max.   :4.400   Max.   :1.900   Max.   :0.600  
##        Species  
##  setosa    :50  
##  versicolor: 0  
##  virginica : 0  
##                 
##                 
##                 
## ------------------------------------------------------------ 
## dat$Species: versicolor
##   Sepal.Length    Sepal.Width     Petal.Length   Petal.Width          Species  
##  Min.   :4.900   Min.   :2.000   Min.   :3.00   Min.   :1.000   setosa    : 0  
##  1st Qu.:5.600   1st Qu.:2.525   1st Qu.:4.00   1st Qu.:1.200   versicolor:50  
##  Median :5.900   Median :2.800   Median :4.35   Median :1.300   virginica : 0  
##  Mean   :5.936   Mean   :2.770   Mean   :4.26   Mean   :1.326                  
##  3rd Qu.:6.300   3rd Qu.:3.000   3rd Qu.:4.60   3rd Qu.:1.500                  
##  Max.   :7.000   Max.   :3.400   Max.   :5.10   Max.   :1.800                  
## ------------------------------------------------------------ 
## dat$Species: virginica
##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.900   Min.   :2.200   Min.   :4.500   Min.   :1.400  
##  1st Qu.:6.225   1st Qu.:2.800   1st Qu.:5.100   1st Qu.:1.800  
##  Median :6.500   Median :3.000   Median :5.550   Median :2.000  
##  Mean   :6.588   Mean   :2.974   Mean   :5.552   Mean   :2.026  
##  3rd Qu.:6.900   3rd Qu.:3.175   3rd Qu.:5.875   3rd Qu.:2.300  
##  Max.   :7.900   Max.   :3.800   Max.   :6.900   Max.   :2.500  
##        Species  
##  setosa    : 0  
##  versicolor: 0  
##  virginica :50  
##                 
##                 
## &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;where the arguments are the name of the dataset, the grouping variable and the summary function. Follow this order, or specify the name of the arguments if you do not follow this order.&lt;/p&gt;
&lt;p&gt;If you need more descriptive statistics, use &lt;code&gt;stat.desc()&lt;/code&gt; from the package &lt;code&gt;{pastecs}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(pastecs)
stat.desc(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##              Sepal.Length  Sepal.Width Petal.Length  Petal.Width Species
## nbr.val      150.00000000 150.00000000  150.0000000 150.00000000      NA
## nbr.null       0.00000000   0.00000000    0.0000000   0.00000000      NA
## nbr.na         0.00000000   0.00000000    0.0000000   0.00000000      NA
## min            4.30000000   2.00000000    1.0000000   0.10000000      NA
## max            7.90000000   4.40000000    6.9000000   2.50000000      NA
## range          3.60000000   2.40000000    5.9000000   2.40000000      NA
## sum          876.50000000 458.60000000  563.7000000 179.90000000      NA
## median         5.80000000   3.00000000    4.3500000   1.30000000      NA
## mean           5.84333333   3.05733333    3.7580000   1.19933333      NA
## SE.mean        0.06761132   0.03558833    0.1441360   0.06223645      NA
## CI.mean.0.95   0.13360085   0.07032302    0.2848146   0.12298004      NA
## var            0.68569351   0.18997942    3.1162779   0.58100626      NA
## std.dev        0.82806613   0.43586628    1.7652982   0.76223767      NA
## coef.var       0.14171126   0.14256420    0.4697441   0.63555114      NA&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can have even more statistics (i.e., skewness, kurtosis and &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normality test&lt;/a&gt;) by adding the argument &lt;code&gt;norm = TRUE&lt;/code&gt; in the previous function. Note that the variable &lt;code&gt;Species&lt;/code&gt; is not numeric, so descriptive statistics cannot be computed for this variable and NA are displayed.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;coefficient-of-variation&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Coefficient of variation&lt;/h1&gt;
&lt;p&gt;The coefficient of variation can be found with &lt;code&gt;stat.desc()&lt;/code&gt; (see the line &lt;code&gt;coef.var&lt;/code&gt; in the table above) or by computing manually (remember that the coefficient of variation is the standard deviation divided by the mean):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sd(dat$Sepal.Length) / mean(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.1417113&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;mode&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Mode&lt;/h1&gt;
&lt;p&gt;To my knowledge there is no function to find the mode of a variable. However, we can easily find it thanks to the functions &lt;code&gt;table()&lt;/code&gt; and &lt;code&gt;sort()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;tab &amp;lt;- table(dat$Sepal.Length) # number of occurrences for each unique value
sort(tab, decreasing = TRUE) # sort highest to lowest&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##   5 5.1 6.3 5.7 6.7 5.5 5.8 6.4 4.9 5.4 5.6   6 6.1 4.8 6.5 4.6 5.2 6.2 6.9 7.7 
##  10   9   9   8   8   7   7   7   6   6   6   6   6   5   5   4   4   4   4   4 
## 4.4 5.9 6.8 7.2 4.7 6.6 4.3 4.5 5.3   7 7.1 7.3 7.4 7.6 7.9 
##   3   3   3   3   2   2   1   1   1   1   1   1   1   1   1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;table()&lt;/code&gt; gives the number of occurrences for each unique value, then &lt;code&gt;sort()&lt;/code&gt; with the argument &lt;code&gt;decreasing = TRUE&lt;/code&gt; displays the number of occurrences from highest to lowest. The mode of the variable &lt;code&gt;Sepal.Length&lt;/code&gt; is thus 5. This code to find the mode can also be applied to qualitative variables such as &lt;code&gt;Species&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sort(table(dat$Species), decreasing = TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##     setosa versicolor  virginica 
##         50         50         50&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summary(dat$Species)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##     setosa versicolor  virginica 
##         50         50         50&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;correlation&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Correlation&lt;/h1&gt;
&lt;p&gt;Another descriptive statistics is the correlation coefficient.&lt;/p&gt;
&lt;p&gt;The correlation measures the &lt;em&gt;linear&lt;/em&gt; relationship between two variables, and it can be computed with the &lt;code&gt;cor()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;cor(dat$Sepal.Length, dat$Sepal.Width)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] -0.1175698&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Computing correlation in R and interpreting the results deserve a detailed explanation, so I wrote an article covering &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;correlation and correlation test&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;contingency-table&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Contingency table&lt;/h1&gt;
&lt;p&gt;&lt;code&gt;table()&lt;/code&gt; introduced above can also be used on two qualitative variables to create a contingency table. The dataset &lt;code&gt;iris&lt;/code&gt; has only one qualitative variable so we create a new qualitative variable just for this example. We create the variable &lt;code&gt;size&lt;/code&gt; which corresponds to &lt;code&gt;small&lt;/code&gt; if the length of the petal is smaller than the median of all flowers, &lt;code&gt;big&lt;/code&gt; otherwise:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat$size &amp;lt;- ifelse(dat$Sepal.Length &amp;lt; median(dat$Sepal.Length),
  &amp;quot;small&amp;quot;, &amp;quot;big&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here is a recap of the occurrences by size:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;table(dat$size)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##   big small 
##    77    73&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We now create a contingency table of the two variables &lt;code&gt;Species&lt;/code&gt; and &lt;code&gt;size&lt;/code&gt; with the &lt;code&gt;table()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;table(dat$Species, dat$size)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             
##              big small
##   setosa       1    49
##   versicolor  29    21
##   virginica   47     3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or with the &lt;code&gt;xtabs()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;xtabs(~ dat$Species + dat$size)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             dat$size
## dat$Species  big small
##   setosa       1    49
##   versicolor  29    21
##   virginica   47     3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The contingency table gives the number of cases in each subgroup. For instance, there is only one big setosa flower, while there are 49 small setosa flowers in the dataset.&lt;/p&gt;
&lt;p&gt;To go further, we can see from the table that setosa flowers seem to be smaller in size than virginica flowers. In order to check whether size is significantly associated with species, we could perform a Chi-square test of independence since both variables are categorical variables. See how to do this test &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-by-hand/&#34;&gt;by hand&lt;/a&gt; and &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;in R&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Note that &lt;code&gt;Species&lt;/code&gt; are in rows and &lt;code&gt;size&lt;/code&gt; in column because we specified &lt;code&gt;Species&lt;/code&gt; and then &lt;code&gt;size&lt;/code&gt; in &lt;code&gt;table()&lt;/code&gt;. Change the order if you want to switch the two variables.&lt;/p&gt;
&lt;p&gt;Instead of having the frequencies (i.e.. the number of cases) you can also have the relative frequencies (i.e., proportions) in each subgroup by adding the &lt;code&gt;table()&lt;/code&gt; function inside the &lt;code&gt;prop.table()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;prop.table(table(dat$Species, dat$size))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             
##                      big       small
##   setosa     0.006666667 0.326666667
##   versicolor 0.193333333 0.140000000
##   virginica  0.313333333 0.020000000&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that you can also compute the percentages by row or by column by adding a second argument to the &lt;code&gt;prop.table()&lt;/code&gt; function: &lt;code&gt;1&lt;/code&gt; for row, or &lt;code&gt;2&lt;/code&gt; for column:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# percentages by row:
round(prop.table(table(dat$Species, dat$size), 1), 2) # round to 2 digits with round()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             
##               big small
##   setosa     0.02  0.98
##   versicolor 0.58  0.42
##   virginica  0.94  0.06&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# percentages by column:
round(prop.table(table(dat$Species, dat$size), 2), 2) # round to 2 digits with round()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             
##               big small
##   setosa     0.01  0.67
##   versicolor 0.38  0.29
##   virginica  0.61  0.04&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;See the section on &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#cross-tabulations-with-ctable&#34;&gt;advanced descriptive statistics&lt;/a&gt; for more advanced contingency tables.&lt;/p&gt;
&lt;div id=&#34;mosaic-plot&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Mosaic plot&lt;/h2&gt;
&lt;p&gt;A mosaic plot allows to visualize a contingency table of two qualitative variables:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mosaicplot(table(dat$Species, dat$size),
  color = TRUE,
  xlab = &amp;quot;Species&amp;quot;, # label for x-axis
  ylab = &amp;quot;Size&amp;quot; # label for y-axis
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-32-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The mosaic plot shows that, for our sample, the proportion of big and small flowers is clearly different between the three species. In particular, the virginica species is the biggest, and the setosa species is the smallest of the three species (in terms of sepal length since the variable &lt;code&gt;size&lt;/code&gt; is based on the variable &lt;code&gt;Sepal.Length&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;For your information, a mosaic plot can also be done via the &lt;code&gt;mosaic()&lt;/code&gt; function from the &lt;code&gt;{vcd}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(vcd)

mosaic(~ Species + size,
  data = dat,
  direction = c(&amp;quot;v&amp;quot;, &amp;quot;h&amp;quot;)
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-33-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;barplot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Barplot&lt;/h1&gt;
&lt;p&gt;Barplots can only be done on qualitative variables (see the difference with a quantitative variable &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/&#34;&gt;here&lt;/a&gt;). A barplot is a tool to visualize the distribution of a qualitative variable. We draw a barplot of the qualitative variable &lt;code&gt;size&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;barplot(table(dat$size)) # table() is mandatory&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-34-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;You can also draw a barplot of the relative frequencies instead of the frequencies by adding &lt;code&gt;prop.table()&lt;/code&gt; as we did earlier:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;barplot(prop.table(table(dat$size)))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-35-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggplot2) # needed each time you open RStudio
# The package ggplot2 must be installed first

ggplot(dat) +
  aes(x = size) +
  geom_bar()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-36-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;histogram&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Histogram&lt;/h1&gt;
&lt;p&gt;A histogram gives an idea about the distribution of a quantitative variable. The idea is to break the range of values into intervals and count how many observations fall into each interval. Histograms are a bit similar to barplots, but histograms are used for quantitative variables whereas barplots are used for qualitative variables. To draw a histogram in R, use &lt;code&gt;hist()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;hist(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-37-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Add the arguments &lt;code&gt;breaks =&lt;/code&gt; inside the &lt;code&gt;hist()&lt;/code&gt; function if you want to change the number of bins. A rule of thumb (known as the square-root rule) is that the number of bins should be the rounded value of the square root of the number of observations. The dataset includes 150 observations so in this case the number of bins can be set to 12.&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Sepal.Length) +
  geom_histogram()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-38-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;By default, the number of bins is 30. You can change this value with &lt;code&gt;geom_histogram(bins = 12)&lt;/code&gt; for instance.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;boxplot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Boxplot&lt;/h1&gt;
&lt;p&gt;Boxplots are really useful in descriptive statistics and are often underused (mostly because it is not well understood by the public). A boxplot graphically represents the distribution of a quantitative variable by visually displaying five common location summary (minimum, median, first/third quartiles and maximum) and any observation that was classified as a suspected &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outlier&lt;/a&gt; using the interquartile range (IQR) criterion.&lt;/p&gt;
&lt;p&gt;The IQR criterion means that all observations above &lt;span class=&#34;math inline&#34;&gt;\(q_{0.75} + 1.5 \cdot IQR\)&lt;/span&gt; or below &lt;span class=&#34;math inline&#34;&gt;\(q_{0.25} - 1.5 \cdot IQR\)&lt;/span&gt; (where &lt;span class=&#34;math inline&#34;&gt;\(q_{0.25}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(q_{0.75}\)&lt;/span&gt; correspond to first and third quartile respectively) are considered as potential outliers by R. The minimum and maximum in the boxplot are represented without these suspected outliers.&lt;/p&gt;
&lt;p&gt;Seeing all these information on the same plot help to have a good first overview of the dispersion and the location of the data. Before drawing a boxplot of our data, see below a graph explaining the information present on a boxplot:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/how-to-interpret-boxplot.png&#34; style=&#34;width:100.0%&#34; alt=&#34;How to interpret a boxplot? Source: LFSAB1105&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;How to interpret a boxplot? Source: LFSAB1105&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;Now an example with our dataset:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;boxplot(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-39-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Boxplots are even more informative when presented side-by-side for comparing and contrasting distributions from two or more groups. For instance, we compare the length of the sepal across the different species:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;boxplot(dat$Sepal.Length ~ dat$Species)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-40-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Species, y = Sepal.Length) +
  geom_boxplot()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-41-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;dotplot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Dotplot&lt;/h1&gt;
&lt;p&gt;A dotplot is more or less similar than a boxplot, except that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;observations are represented as points&lt;/li&gt;
&lt;li&gt;it does not easily tell us about the median, first and third quartiles.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(lattice)

dotplot(dat$Sepal.Length ~ dat$Species)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-42-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Species, y = Sepal.Length) +
  geom_dotplot(binaxis = &amp;quot;y&amp;quot;, stackdir = &amp;quot;center&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-43-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The advantage of using &lt;code&gt;{ggplot2}&lt;/code&gt; over &lt;code&gt;{lattice}&lt;/code&gt; for this plot is that we can easily see the mode.&lt;/p&gt;
&lt;p&gt;Note that a dotplot is particularly useful when there are a limited number of observations, whereas a boxplot is more appropriate with large datasets.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;scatterplot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Scatterplot&lt;/h1&gt;
&lt;p&gt;Scatterplots allow to check whether there is a potential link between two quantitative variables. For this reason, scatterplots are often used to visualize a potential &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;correlation&lt;/a&gt; between two variables. For instance, when drawing a scatterplot of the length of the sepal and the length of the petal:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(dat$Sepal.Length, dat$Petal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-44-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;There seems to be a positive association between the two variables.&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Sepal.Length, y = Petal.Length) +
  geom_point()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-45-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Like boxplots, scatterplots are even more informative when differentiating the points according to a factor, in this case the species:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Sepal.Length, y = Petal.Length, colour = Species) +
  geom_point() +
  scale_color_hue()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-46-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;line-plot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Line plot&lt;/h1&gt;
&lt;p&gt;Line plots, particularly useful in time series or finance, can be created by adding the &lt;code&gt;type = &#34;l&#34;&lt;/code&gt; argument in the &lt;code&gt;plot()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(dat$Sepal.Length,
  type = &amp;quot;l&amp;quot;
) # &amp;quot;l&amp;quot; for line&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-47-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;qq-plot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;QQ-plot&lt;/h1&gt;
&lt;div id=&#34;for-a-single-variable&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;For a single variable&lt;/h2&gt;
&lt;p&gt;In order to check the normality assumption of a variable (normality means that the data follow a normal distribution, also known as a Gaussian distribution), we usually use histograms and/or QQ-plots.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; See an article discussing about the &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution and how to evaluate the normality assumption in R&lt;/a&gt; if you need a refresh on that subject.&lt;/p&gt;
&lt;p&gt;Histograms have been presented earlier, so here is how to draw a QQ-plot:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Draw points on the qq-plot:
qqnorm(dat$Sepal.Length)
# Draw the reference line:
qqline(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-48-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Or a QQ-plot with confidence bands with the &lt;code&gt;qqPlot()&lt;/code&gt; function from the &lt;code&gt;{car}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(car) # package must be installed first
qqPlot(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-49-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## [1] 132 118&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If points are close to the reference line (sometimes referred as Henry’s line) and within the confidence bands, the normality assumption can be considered as met. The bigger the deviation between the points and the reference line and the more they lie outside the confidence bands, the less likely that the normality condition is met. The variable &lt;code&gt;Sepal.Length&lt;/code&gt; does not seem to follow a normal distribution because several points lie outside the confidence bands. When facing a non-normal distribution, the first step is usually to apply the logarithm transformation on the data and recheck to see whether the log-transformed data are normally distributed. Applying the logarithm transformation can be done with the &lt;code&gt;log()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggpubr}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggpubr)
ggqqplot(dat$Sepal.Length)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-50-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;by-groups&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;By groups&lt;/h2&gt;
&lt;p&gt;For some &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt;, the normality assumption is required in all groups. One solution is to draw a QQ-plot for each group by manually splitting the dataset into different groups and then draw a QQ-plot for each subset of the data (with the methods shown above). Another (easier) solution is to draw a QQ-plot for each group automatically with the argument &lt;code&gt;groups =&lt;/code&gt; in the function &lt;code&gt;qqPlot()&lt;/code&gt; from the &lt;code&gt;{car}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;qqPlot(dat$Sepal.Length, groups = dat$size)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-51-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;qplot(
  sample = Sepal.Length, data = dat,
  col = size, shape = size
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-52-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;It is also possible to differentiate groups by only shape or color. For this, remove one of the argument &lt;code&gt;col&lt;/code&gt; or &lt;code&gt;shape&lt;/code&gt; in the &lt;code&gt;qplot()&lt;/code&gt; function above.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;density-plot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Density plot&lt;/h1&gt;
&lt;p&gt;Density plot is a smoothed version of the histogram and is used in the same concept, that is, to represent the distribution of a numeric variable. The functions &lt;code&gt;plot()&lt;/code&gt; and &lt;code&gt;density()&lt;/code&gt; are used together to draw a density plot:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(density(dat$Sepal.Length))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-53-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;{ggplot2}&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(dat) +
  aes(x = Sepal.Length) +
  geom_density()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-in-r_files/figure-html/unnamed-chunk-54-1.png&#34; alt=&#34;&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;correlation-plot&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Correlation plot&lt;/h1&gt;
&lt;p&gt;The last type of descriptive plot is a correlation plot, also called a correlogram. This type of graph is more complex than the ones presented above, so it is detailed in a separate article. See &lt;a href=&#34;https://statsandr.com/blog/correlogram-in-r-how-to-highlight-the-most-correlated-variables-in-a-dataset/&#34;&gt;how to draw a correlogram to highlight the most correlated variables in a dataset&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;advanced-descriptive-statistics&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Advanced descriptive statistics&lt;/h1&gt;
&lt;p&gt;We covered the main functions to compute the most common and basic descriptive statistics. There are, however, many more functions and packages to perform more advanced descriptive statistics in R. In this section, I present some of them with applications to our dataset.&lt;/p&gt;
&lt;div id=&#34;summarytools-package&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;&lt;code&gt;{summarytools}&lt;/code&gt; package&lt;/h2&gt;
&lt;p&gt;One package for descriptive statistics I often use for my projects in R is the &lt;a href=&#34;https://cran.r-project.org/web/packages/summarytools/index.html&#34; target=&#34;_blank&#34;&gt;&lt;code&gt;{summarytools}&lt;/code&gt;&lt;/a&gt; package. The package is centered around 4 functions:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;code&gt;freq()&lt;/code&gt; for frequencies tables&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ctable()&lt;/code&gt; for cross-tabulations&lt;/li&gt;
&lt;li&gt;&lt;code&gt;descr()&lt;/code&gt; for descriptive statistics&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfSummary()&lt;/code&gt; for dataframe summaries&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;A combination of these 4 functions is usually more than enough for most descriptive analyses. Moreover, the package has been built with &lt;a href=&#34;https://statsandr.com/blog/getting-started-in-r-markdown/&#34;&gt;R Markdown&lt;/a&gt; in mind, meaning that outputs render well in HTML reports. And for non-English speakers, built-in translations exist for French, Portuguese, Spanish, Russian and Turkish.&lt;/p&gt;
&lt;p&gt;I illustrate each of the 4 functions in the following sections. Outputs that follow display much better in R Markdown reports, but in this article I limit myself to the raw outputs as the goal is to show how the functions work, not how to make them render well. See the setup settings in the &lt;a href=&#34;https://cran.r-project.org/web/packages/summarytools/vignettes/introduction.html&#34; target=&#34;_blank&#34;&gt;vignette&lt;/a&gt; of the package if you want to print the outputs in a nice way in R Markdown.&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;div id=&#34;frequency-tables-with-freq&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Frequency tables with &lt;code&gt;freq()&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;freq()&lt;/code&gt; function produces frequency tables with frequencies, proportions, as well as missing data information.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(summarytools)
freq(dat$Species)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Frequencies  
## dat$Species  
## Type: Factor  
## 
##                    Freq   % Valid   % Valid Cum.   % Total   % Total Cum.
## ---------------- ------ --------- -------------- --------- --------------
##           setosa     50     33.33          33.33     33.33          33.33
##       versicolor     50     33.33          66.67     33.33          66.67
##        virginica     50     33.33         100.00     33.33         100.00
##             &amp;lt;NA&amp;gt;      0                               0.00         100.00
##            Total    150    100.00         100.00    100.00         100.00&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you do not need information about missing values, add the &lt;code&gt;report.nas = FALSE&lt;/code&gt; argument:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;freq(dat$Species,
  report.nas = FALSE # remove NA information
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Frequencies  
## dat$Species  
## Type: Factor  
## 
##                    Freq        %   % Cum.
## ---------------- ------ -------- --------
##           setosa     50    33.33    33.33
##       versicolor     50    33.33    66.67
##        virginica     50    33.33   100.00
##            Total    150   100.00   100.00&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And for a minimalist output with only counts and proportions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;freq(dat$Species,
  report.nas = FALSE, # remove NA information
  totals = FALSE, # remove totals
  cumul = FALSE, # remove cumuls
  headings = FALSE # remove headings
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##                    Freq       %
## ---------------- ------ -------
##           setosa     50   33.33
##       versicolor     50   33.33
##        virginica     50   33.33&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;cross-tabulations-with-ctable&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Cross-tabulations with &lt;code&gt;ctable()&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;ctable()&lt;/code&gt; function produces cross-tabulations (also known as contingency tables) for pairs of categorical variables. Using the two categorical variables in our dataset:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ctable(
  x = dat$Species,
  y = dat$size
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Cross-Tabulation, Row Proportions  
## Species * size  
## Data Frame: dat  
## 
## ------------ ------ ------------ ------------ --------------
##                size          big        small          Total
##      Species                                                
##       setosa           1 ( 2.0%)   49 (98.0%)    50 (100.0%)
##   versicolor          29 (58.0%)   21 (42.0%)    50 (100.0%)
##    virginica          47 (94.0%)    3 ( 6.0%)    50 (100.0%)
##        Total          77 (51.3%)   73 (48.7%)   150 (100.0%)
## ------------ ------ ------------ ------------ --------------&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Row proportions are shown by default. To display column or total proportions, add the &lt;code&gt;prop = &#34;c&#34;&lt;/code&gt; or &lt;code&gt;prop = &#34;t&#34;&lt;/code&gt; arguments, respectively:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ctable(
  x = dat$Species,
  y = dat$size,
  prop = &amp;quot;t&amp;quot; # total proportions
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Cross-Tabulation, Total Proportions  
## Species * size  
## Data Frame: dat  
## 
## ------------ ------ ------------ ------------ --------------
##                size          big        small          Total
##      Species                                                
##       setosa           1 ( 0.7%)   49 (32.7%)    50 ( 33.3%)
##   versicolor          29 (19.3%)   21 (14.0%)    50 ( 33.3%)
##    virginica          47 (31.3%)    3 ( 2.0%)    50 ( 33.3%)
##        Total          77 (51.3%)   73 (48.7%)   150 (100.0%)
## ------------ ------ ------------ ------------ --------------&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To remove proportions altogether, add the argument &lt;code&gt;prop = &#34;n&#34;&lt;/code&gt;. Furthermore, to display only the bare minimum, add the &lt;code&gt;totals = FALSE&lt;/code&gt; and &lt;code&gt;headings = FALSE&lt;/code&gt; arguments:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ctable(
  x = dat$Species,
  y = dat$size,
  prop = &amp;quot;n&amp;quot;, # remove proportions
  totals = FALSE, # remove totals
  headings = FALSE # remove headings
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## ------------ ------ ----- -------
##                size   big   small
##      Species                     
##       setosa            1      49
##   versicolor           29      21
##    virginica           47       3
## ------------ ------ ----- -------&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is equivalent than &lt;code&gt;table(dat$Species, dat$size)&lt;/code&gt; and &lt;code&gt;xtabs(~ dat$Species + dat$size)&lt;/code&gt; performed in the section on &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#contingency-table&#34;&gt;contingency tables&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;To display results of the &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;Chi-square test of independence&lt;/a&gt;, add the &lt;code&gt;chisq = TRUE&lt;/code&gt; argument:&lt;a href=&#34;#fn3&#34; class=&#34;footnote-ref&#34; id=&#34;fnref3&#34;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ctable(
  x = dat$Species,
  y = dat$size,
  chisq = TRUE, # display results of Chi-square test of independence
  headings = FALSE # remove headings
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## ------------ ------ ------------ ------------ --------------
##                size          big        small          Total
##      Species                                                
##       setosa           1 ( 2.0%)   49 (98.0%)    50 (100.0%)
##   versicolor          29 (58.0%)   21 (42.0%)    50 (100.0%)
##    virginica          47 (94.0%)    3 ( 6.0%)    50 (100.0%)
##        Total          77 (51.3%)   73 (48.7%)   150 (100.0%)
## ------------ ------ ------------ ------------ --------------
## 
## ----------------------------
##  Chi.squared   df   p.value 
## ------------- ---- ---------
##    86.0345     2       0    
## ----------------------------&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;p&lt;/em&gt;-value is close to 0 so we reject the null hypothesis of independence between the two variables. In our context, this indicates that species and size are dependent and that there is a significant relationship between the two variables.&lt;/p&gt;
&lt;p&gt;It is also possible to create a contingency table for each level of a third categorical variable thanks to the combination of the &lt;code&gt;stby()&lt;/code&gt; and &lt;code&gt;ctable()&lt;/code&gt; functions. There are only 2 categorical variables in our dataset, so let’s use the &lt;code&gt;tabacco&lt;/code&gt; dataset which has 4 categorical variables (i.e., gender, age group, smoker, diseased). For this example, we would like to create a contingency table of the variables &lt;code&gt;smoker&lt;/code&gt; and &lt;code&gt;diseased&lt;/code&gt;, and this for each &lt;code&gt;gender&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;stby(
  list(
    x = tobacco$smoker, # smoker and diseased
    y = tobacco$diseased
  ),
  INDICES = tobacco$gender, # for each gender
  FUN = ctable # ctable for cross-tabulation
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Cross-Tabulation, Row Proportions  
## smoker * diseased  
## Data Frame: tobacco  
## Group: gender = F  
## 
## -------- ---------- ------------- ------------- --------------
##            diseased           Yes            No          Total
##   smoker                                                      
##      Yes               62 (42.2%)    85 (57.8%)   147 (100.0%)
##       No               49 (14.3%)   293 (85.7%)   342 (100.0%)
##    Total              111 (22.7%)   378 (77.3%)   489 (100.0%)
## -------- ---------- ------------- ------------- --------------
## 
## Group: gender = M  
## 
## -------- ---------- ------------- ------------- --------------
##            diseased           Yes            No          Total
##   smoker                                                      
##      Yes               63 (44.1%)    80 (55.9%)   143 (100.0%)
##       No               47 (13.6%)   299 (86.4%)   346 (100.0%)
##    Total              110 (22.5%)   379 (77.5%)   489 (100.0%)
## -------- ---------- ------------- ------------- --------------&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;descriptive-statistics-with-descr&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Descriptive statistics with &lt;code&gt;descr()&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;descr()&lt;/code&gt; function produces descriptive (univariate) statistics with common central tendency statistics and measures of dispersion. (See the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#location-versus-dispersion-measures&#34;&gt;difference between a measure of central tendency and dispersion&lt;/a&gt; if you need a reminder.)&lt;/p&gt;
&lt;p&gt;A major advantage of this function is that it accepts single vectors as well as data frames. If a data frame is provided, all non-numerical columns are ignored so you do not have to remove them yourself before running the function.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;descr()&lt;/code&gt; function allows to display:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;only a selection of descriptive statistics of your choice, with the &lt;code&gt;stats = c(&#34;mean&#34;, &#34;sd&#34;)&lt;/code&gt; argument for mean and standard deviation for example&lt;/li&gt;
&lt;li&gt;the minimum, first quartile, median, third quartile and maximum with &lt;code&gt;stats = &#34;fivenum&#34;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;the most common descriptive statistics (mean, standard deviation, minimum, median, maximum, number and percentage of valid observations), with &lt;code&gt;stats = &#34;common&#34;&lt;/code&gt;:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;descr(dat,
  headings = FALSE, # remove headings
  stats = &amp;quot;common&amp;quot; # most common descriptive statistics
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##                   Petal.Length   Petal.Width   Sepal.Length   Sepal.Width
## --------------- -------------- ------------- -------------- -------------
##            Mean           3.76          1.20           5.84          3.06
##         Std.Dev           1.77          0.76           0.83          0.44
##             Min           1.00          0.10           4.30          2.00
##          Median           4.35          1.30           5.80          3.00
##             Max           6.90          2.50           7.90          4.40
##         N.Valid         150.00        150.00         150.00        150.00
##               N         150.00        150.00         150.00        150.00
##       Pct.Valid         100.00        100.00         100.00        100.00&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Tip:&lt;/em&gt; if you have a large number of variables, add the &lt;code&gt;transpose = TRUE&lt;/code&gt; argument for a better display.&lt;/p&gt;
&lt;p&gt;In order to compute these descriptive statistics by group (e.g., &lt;code&gt;Species&lt;/code&gt; in our dataset), use the &lt;code&gt;descr()&lt;/code&gt; function in combination with the &lt;code&gt;stby()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;stby(
  data = dat,
  INDICES = dat$Species, # by Species
  FUN = descr, # descriptive statistics
  stats = &amp;quot;common&amp;quot; # most common descr. stats
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Descriptive Statistics  
## dat  
## Group: Species = setosa  
## N: 50  
## 
##                   Petal.Length   Petal.Width   Sepal.Length   Sepal.Width
## --------------- -------------- ------------- -------------- -------------
##            Mean           1.46          0.25           5.01          3.43
##         Std.Dev           0.17          0.11           0.35          0.38
##             Min           1.00          0.10           4.30          2.30
##          Median           1.50          0.20           5.00          3.40
##             Max           1.90          0.60           5.80          4.40
##         N.Valid          50.00         50.00          50.00         50.00
##               N          50.00         50.00          50.00         50.00
##       Pct.Valid         100.00        100.00         100.00        100.00
## 
## Group: Species = versicolor  
## N: 50  
## 
##                   Petal.Length   Petal.Width   Sepal.Length   Sepal.Width
## --------------- -------------- ------------- -------------- -------------
##            Mean           4.26          1.33           5.94          2.77
##         Std.Dev           0.47          0.20           0.52          0.31
##             Min           3.00          1.00           4.90          2.00
##          Median           4.35          1.30           5.90          2.80
##             Max           5.10          1.80           7.00          3.40
##         N.Valid          50.00         50.00          50.00         50.00
##               N          50.00         50.00          50.00         50.00
##       Pct.Valid         100.00        100.00         100.00        100.00
## 
## Group: Species = virginica  
## N: 50  
## 
##                   Petal.Length   Petal.Width   Sepal.Length   Sepal.Width
## --------------- -------------- ------------- -------------- -------------
##            Mean           5.55          2.03           6.59          2.97
##         Std.Dev           0.55          0.27           0.64          0.32
##             Min           4.50          1.40           4.90          2.20
##          Median           5.55          2.00           6.50          3.00
##             Max           6.90          2.50           7.90          3.80
##         N.Valid          50.00         50.00          50.00         50.00
##               N          50.00         50.00          50.00         50.00
##       Pct.Valid         100.00        100.00         100.00        100.00&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;data-frame-summaries-with-dfsummary&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Data frame summaries with &lt;code&gt;dfSummary()&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;dfSummary()&lt;/code&gt; function generates a summary table with statistics, frequencies and graphs for all variables in a dataset. The information shown depends on the type of the variables (character, factor, numeric, date) and also varies according to the number of distinct values.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dfSummary(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Data Frame Summary  
## dat  
## Dimensions: 150 x 6  
## Duplicates: 1  
## 
## -----------------------------------------------------------------------------------------------------------
## No   Variable       Stats / Values          Freqs (% of Valid)   Graph                 Valid      Missing  
## ---- -------------- ----------------------- -------------------- --------------------- ---------- ---------
## 1    Sepal.Length   Mean (sd) : 5.8 (0.8)   35 distinct values     . . : :             150        0        
##      [numeric]      min &amp;lt; med &amp;lt; max:                               : : : :             (100.0%)   (0.0%)   
##                     4.3 &amp;lt; 5.8 &amp;lt; 7.9                                : : : : :                               
##                     IQR (CV) : 1.3 (0.1)                           : : : : :                               
##                                                                  : : : : : : : :                           
## 
## 2    Sepal.Width    Mean (sd) : 3.1 (0.4)   23 distinct values           :             150        0        
##      [numeric]      min &amp;lt; med &amp;lt; max:                                     :             (100.0%)   (0.0%)   
##                     2 &amp;lt; 3 &amp;lt; 4.4                                        . :                                 
##                     IQR (CV) : 0.5 (0.1)                             : : : :                               
##                                                                  . . : : : : : :                           
## 
## 3    Petal.Length   Mean (sd) : 3.8 (1.8)   43 distinct values   :                     150        0        
##      [numeric]      min &amp;lt; med &amp;lt; max:                             :         . :         (100.0%)   (0.0%)   
##                     1 &amp;lt; 4.3 &amp;lt; 6.9                                :         : : .                           
##                     IQR (CV) : 3.5 (0.5)                         : :       : : : .                         
##                                                                  : :   . : : : : : .                       
## 
## 4    Petal.Width    Mean (sd) : 1.2 (0.8)   22 distinct values   :                     150        0        
##      [numeric]      min &amp;lt; med &amp;lt; max:                             :                     (100.0%)   (0.0%)   
##                     0.1 &amp;lt; 1.3 &amp;lt; 2.5                              :       . .   :                           
##                     IQR (CV) : 1.5 (0.6)                         :       : :   :   .                       
##                                                                  : :   : : : . : : :                       
## 
## 5    Species        1. setosa               50 (33.3%)           IIIIII                150        0        
##      [factor]       2. versicolor           50 (33.3%)           IIIIII                (100.0%)   (0.0%)   
##                     3. virginica            50 (33.3%)           IIIIII                                    
## 
## 6    size           1. big                  77 (51.3%)           IIIIIIIIII            150        0        
##      [character]    2. small                73 (48.7%)           IIIIIIIII             (100.0%)   (0.0%)   
## -----------------------------------------------------------------------------------------------------------&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;describeby-from-the-psych-package&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;&lt;code&gt;describeBy()&lt;/code&gt; from the &lt;code&gt;{psych}&lt;/code&gt; package&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;describeBy()&lt;/code&gt; function from the &lt;code&gt;{psych}&lt;/code&gt; package allows to report several summary statistics (i.e., number of valid cases, mean, standard deviation, median, trimmed mean, mad: median absolute deviation (from the median), minimum, maximum, range, skewness and kurtosis) by a grouping variable.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(psych)
describeBy(
  dat,
  dat$Species # grouping variable
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##  Descriptive statistics by group 
## group: setosa
##              vars  n mean   sd median trimmed  mad min max range  skew kurtosis
## Sepal.Length    1 50 5.01 0.35    5.0    5.00 0.30 4.3 5.8   1.5  0.11    -0.45
## Sepal.Width     2 50 3.43 0.38    3.4    3.42 0.37 2.3 4.4   2.1  0.04     0.60
## Petal.Length    3 50 1.46 0.17    1.5    1.46 0.15 1.0 1.9   0.9  0.10     0.65
## Petal.Width     4 50 0.25 0.11    0.2    0.24 0.00 0.1 0.6   0.5  1.18     1.26
## Species         5 50 1.00 0.00    1.0    1.00 0.00 1.0 1.0   0.0   NaN      NaN
## size            6 50 1.98 0.14    2.0    2.00 0.00 1.0 2.0   1.0 -6.65    43.12
##                se
## Sepal.Length 0.05
## Sepal.Width  0.05
## Petal.Length 0.02
## Petal.Width  0.01
## Species      0.00
## size         0.02
## ------------------------------------------------------------ 
## group: versicolor
##              vars  n mean   sd median trimmed  mad min max range  skew kurtosis
## Sepal.Length    1 50 5.94 0.52   5.90    5.94 0.52 4.9 7.0   2.1  0.10    -0.69
## Sepal.Width     2 50 2.77 0.31   2.80    2.78 0.30 2.0 3.4   1.4 -0.34    -0.55
## Petal.Length    3 50 4.26 0.47   4.35    4.29 0.52 3.0 5.1   2.1 -0.57    -0.19
## Petal.Width     4 50 1.33 0.20   1.30    1.32 0.22 1.0 1.8   0.8 -0.03    -0.59
## Species         5 50 2.00 0.00   2.00    2.00 0.00 2.0 2.0   0.0   NaN      NaN
## size            6 50 1.42 0.50   1.00    1.40 0.00 1.0 2.0   1.0  0.31    -1.94
##                se
## Sepal.Length 0.07
## Sepal.Width  0.04
## Petal.Length 0.07
## Petal.Width  0.03
## Species      0.00
## size         0.07
## ------------------------------------------------------------ 
## group: virginica
##              vars  n mean   sd median trimmed  mad min max range  skew kurtosis
## Sepal.Length    1 50 6.59 0.64   6.50    6.57 0.59 4.9 7.9   3.0  0.11    -0.20
## Sepal.Width     2 50 2.97 0.32   3.00    2.96 0.30 2.2 3.8   1.6  0.34     0.38
## Petal.Length    3 50 5.55 0.55   5.55    5.51 0.67 4.5 6.9   2.4  0.52    -0.37
## Petal.Width     4 50 2.03 0.27   2.00    2.03 0.30 1.4 2.5   1.1 -0.12    -0.75
## Species         5 50 3.00 0.00   3.00    3.00 0.00 3.0 3.0   0.0   NaN      NaN
## size            6 50 1.06 0.24   1.00    1.00 0.00 1.0 2.0   1.0  3.59    11.15
##                se
## Sepal.Length 0.09
## Sepal.Width  0.05
## Petal.Length 0.08
## Petal.Width  0.04
## Species      0.00
## size         0.03&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;aggregate-function&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;&lt;code&gt;aggregate()&lt;/code&gt; function&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;aggregate()&lt;/code&gt; function allows to split the data into subsets and then to compute summary statistics for each. For instance, if we want to compute the mean for the variables &lt;code&gt;Sepal.Length&lt;/code&gt; and &lt;code&gt;Sepal.Width&lt;/code&gt; by &lt;code&gt;Species&lt;/code&gt; and &lt;code&gt;Size&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;aggregate(cbind(Sepal.Length, Sepal.Width) ~ Species + size,
  data = dat,
  mean
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      Species  size Sepal.Length Sepal.Width
## 1     setosa   big     5.800000    4.000000
## 2 versicolor   big     6.282759    2.868966
## 3  virginica   big     6.663830    2.997872
## 4     setosa small     4.989796    3.416327
## 5 versicolor small     5.457143    2.633333
## 6  virginica small     5.400000    2.600000&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;summaryby-from-doby&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;&lt;code&gt;summaryBy()&lt;/code&gt; from &lt;code&gt;{doBy}&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;An alternative is the &lt;code&gt;summaryBy()&lt;/code&gt; function from the &lt;code&gt;{doBy}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# summary statistics by group
library(doBy)
summaryBy(Sepal.Length + Sepal.Width ~ Species,
  data = dat,
  FUN = summary
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      Species Sepal.Length.Min. Sepal.Length.1st Qu. Sepal.Length.Median
## 1     setosa               4.3                4.800                 5.0
## 2 versicolor               4.9                5.600                 5.9
## 3  virginica               4.9                6.225                 6.5
##   Sepal.Length.Mean Sepal.Length.3rd Qu. Sepal.Length.Max. Sepal.Width.Min.
## 1             5.006                  5.2               5.8              2.3
## 2             5.936                  6.3               7.0              2.0
## 3             6.588                  6.9               7.9              2.2
##   Sepal.Width.1st Qu. Sepal.Width.Median Sepal.Width.Mean Sepal.Width.3rd Qu.
## 1               3.200                3.4            3.428               3.675
## 2               2.525                2.8            2.770               3.000
## 3               2.800                3.0            2.974               3.175
##   Sepal.Width.Max.
## 1              4.4
## 2              3.4
## 3              3.8&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you are interested in some specific descriptive statistics, you can easily specify them via the &lt;code&gt;FUN&lt;/code&gt; argument:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;summaryBy(Sepal.Length + Sepal.Width ~ Species,
  data = dat,
  FUN = c(mean, var)
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      Species Sepal.Length.mean Sepal.Width.mean Sepal.Length.var
## 1     setosa             5.006            3.428        0.1242490
## 2 versicolor             5.936            2.770        0.2664327
## 3  virginica             6.588            2.974        0.4043429
##   Sepal.Width.var
## 1      0.14368980
## 2      0.09846939
## 3      0.10400408&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;group_by-and-summarise-from-dplyr&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;&lt;code&gt;group_by()&lt;/code&gt; and &lt;code&gt;summarise()&lt;/code&gt; from &lt;code&gt;{dplyr}&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;Another alternative is with the &lt;code&gt;summarise()&lt;/code&gt; and &lt;code&gt;group_by()&lt;/code&gt; functions from the &lt;code&gt;{dplyr}&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(dplyr)

group_by(dat, Species) %&amp;gt;%
  summarise(
    mean = mean(Sepal.Length, na.rm = TRUE),
    sd = sd(Sepal.Length, na.rm = TRUE)
  )&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 3 × 3
##   Species     mean    sd
##   &amp;lt;fct&amp;gt;      &amp;lt;dbl&amp;gt; &amp;lt;dbl&amp;gt;
## 1 setosa      5.01 0.352
## 2 versicolor  5.94 0.516
## 3 virginica   6.59 0.636&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to do descriptive statistics in R. If you would like to do the same by hand or understand what these statistics represent, I invite you to read the article “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;Descriptive statistics by hand&lt;/a&gt;”.&lt;/p&gt;
&lt;p&gt;As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;(Note that this article is available for download on my &lt;a href=&#34;https://statsandr.gumroad.com/&#34;&gt;Gumroad page&lt;/a&gt;.)&lt;/em&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;Normality tests such as Shapiro-Wilk or Kolmogorov-Smirnov tests can also be used to test whether the data follow a normal distribution or not. However, in practice, normality tests are often considered as too conservative in the sense that for large sample size, a small deviation from the normality may cause the normality condition to be violated. For this reason, it is often the case that the normality condition is verified based on a combination of visual inspections (with histograms and QQ-plots) and formal test (Shapiro-Wilk test for instance).&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;Note that the &lt;code&gt;plain.ascii&lt;/code&gt; and &lt;code&gt;style&lt;/code&gt; arguments are needed for this package. In our examples, these arguments are added in the settings of each chunk so they are not visible.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn3&#34;&gt;&lt;p&gt;Note that it is also possible to compute odds ratio and risk ratio. See the vignette of the package for more information on this matter as these ratios are beyond the scope of this article.&lt;a href=&#34;#fnref3&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Descriptive statistics by hand</title>
      <link>https://statsandr.com/blog/descriptive-statistics-by-hand/</link>
      <pubDate>Sun, 19 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/descriptive-statistics-by-hand/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#location-versus-dispersion-measures&#34; id=&#34;toc-location-versus-dispersion-measures&#34;&gt;Location versus dispersion measures&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#location&#34; id=&#34;toc-location&#34;&gt;Location&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#minimum-and-maximum&#34; id=&#34;toc-minimum-and-maximum&#34;&gt;Minimum and maximum&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#mean&#34; id=&#34;toc-mean&#34;&gt;Mean&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#median&#34; id=&#34;toc-median&#34;&gt;Median&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#odd-number-of-observations&#34; id=&#34;toc-odd-number-of-observations&#34;&gt;Odd number of observations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#even-number-of-observations&#34; id=&#34;toc-even-number-of-observations&#34;&gt;Even number of observations&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#mean-vs.-median&#34; id=&#34;toc-mean-vs.-median&#34;&gt;Mean vs. median&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#st-and-3rd-quartiles&#34; id=&#34;toc-st-and-3rd-quartiles&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(1^{st}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(3^{rd}\)&lt;/span&gt; quartiles&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#q_0.25-q_0.75-and-q_0.5&#34; id=&#34;toc-q_0.25-q_0.75-and-q_0.5&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(q_{0.25}\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(q_{0.75}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(q_{0.5}\)&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#a-note-on-deciles-and-percentiles&#34; id=&#34;toc-a-note-on-deciles-and-percentiles&#34;&gt;A note on deciles and percentiles&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#mode&#34; id=&#34;toc-mode&#34;&gt;Mode&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#quantitative-variables&#34; id=&#34;toc-quantitative-variables&#34;&gt;Quantitative variables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#qualitative-variables&#34; id=&#34;toc-qualitative-variables&#34;&gt;Qualitative variables&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#dispersion&#34; id=&#34;toc-dispersion&#34;&gt;Dispersion&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#range&#34; id=&#34;toc-range&#34;&gt;Range&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#standard-deviation&#34; id=&#34;toc-standard-deviation&#34;&gt;Standard deviation&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#standard-deviation-for-a-population&#34; id=&#34;toc-standard-deviation-for-a-population&#34;&gt;Standard deviation for a population&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#standard-deviation-for-a-sample&#34; id=&#34;toc-standard-deviation-for-a-sample&#34;&gt;Standard deviation for a sample&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#variance&#34; id=&#34;toc-variance&#34;&gt;Variance&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#variance-for-a-population&#34; id=&#34;toc-variance-for-a-population&#34;&gt;Variance for a population&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#variance-for-a-sample&#34; id=&#34;toc-variance-for-a-sample&#34;&gt;Variance for a sample&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#standard-deviation-vs.-variance&#34; id=&#34;toc-standard-deviation-vs.-variance&#34;&gt;Standard deviation vs. variance&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#notations&#34; id=&#34;toc-notations&#34;&gt;Notations&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#interquartile-range&#34; id=&#34;toc-interquartile-range&#34;&gt;Interquartile range&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#coefficient-of-variation&#34; id=&#34;toc-coefficient-of-variation&#34;&gt;Coefficient of variation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#coefficient-of-variation-vs.-standard-deviation&#34; id=&#34;toc-coefficient-of-variation-vs.-standard-deviation&#34;&gt;Coefficient of variation vs. standard deviation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand_files/descriptive-statistics-by-hand.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;This article explains how to compute the main descriptive statistics by hand and how to interpret them. To learn how to compute these measures in R, read the article “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;Descriptive statistics in R&lt;/a&gt;”.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Descriptive statistics&lt;/strong&gt; (in the broad sense of the term) is a branch of statistics aiming at &lt;strong&gt;summarizing, describing and presenting a series of values or a dataset&lt;/strong&gt;. Long series of values without any preparation or without any summary measures are often not informative due to the difficulty of recognizing any pattern in the data. Below an example with the height (in cm) of a population of 100 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;188.7&lt;/em&gt;, &lt;em&gt;169.4&lt;/em&gt;, &lt;em&gt;178.6&lt;/em&gt;, &lt;em&gt;181.3&lt;/em&gt;, &lt;em&gt;179&lt;/em&gt;, &lt;em&gt;173.9&lt;/em&gt;, &lt;em&gt;190.1&lt;/em&gt;, &lt;em&gt;174.1&lt;/em&gt;, &lt;em&gt;195.2&lt;/em&gt;, &lt;em&gt;174.4&lt;/em&gt;, &lt;em&gt;188&lt;/em&gt;, &lt;em&gt;197.9&lt;/em&gt;, &lt;em&gt;161.1&lt;/em&gt;, &lt;em&gt;172.2&lt;/em&gt;, &lt;em&gt;173.7&lt;/em&gt;, &lt;em&gt;181.4&lt;/em&gt;, &lt;em&gt;172.2&lt;/em&gt;, &lt;em&gt;148.4&lt;/em&gt;, &lt;em&gt;150.6&lt;/em&gt;, &lt;em&gt;188.2&lt;/em&gt;, &lt;em&gt;171.9&lt;/em&gt;, &lt;em&gt;157.2&lt;/em&gt;, &lt;em&gt;173.3&lt;/em&gt;, &lt;em&gt;187.1&lt;/em&gt;, &lt;em&gt;194&lt;/em&gt;, &lt;em&gt;170.7&lt;/em&gt;, &lt;em&gt;172.4&lt;/em&gt;, &lt;em&gt;157.4&lt;/em&gt;, &lt;em&gt;179.6&lt;/em&gt;, &lt;em&gt;168.6&lt;/em&gt;, &lt;em&gt;179.6&lt;/em&gt;, &lt;em&gt;182&lt;/em&gt;, &lt;em&gt;185.4&lt;/em&gt;, &lt;em&gt;168.9&lt;/em&gt;, &lt;em&gt;180&lt;/em&gt;, &lt;em&gt;157.8&lt;/em&gt;, &lt;em&gt;167.2&lt;/em&gt;, &lt;em&gt;166.5&lt;/em&gt;, &lt;em&gt;150.9&lt;/em&gt;, &lt;em&gt;175.4&lt;/em&gt;, &lt;em&gt;177.1&lt;/em&gt;, &lt;em&gt;171.4&lt;/em&gt;, &lt;em&gt;182.6&lt;/em&gt;, &lt;em&gt;167.7&lt;/em&gt;, &lt;em&gt;161.3&lt;/em&gt;, &lt;em&gt;179.3&lt;/em&gt;, &lt;em&gt;166.9&lt;/em&gt;, &lt;em&gt;189.4&lt;/em&gt;, &lt;em&gt;170.7&lt;/em&gt;, &lt;em&gt;181.6&lt;/em&gt;, &lt;em&gt;178.2&lt;/em&gt;, &lt;em&gt;167.2&lt;/em&gt;, &lt;em&gt;190.8&lt;/em&gt;, &lt;em&gt;181.4&lt;/em&gt;, &lt;em&gt;175.9&lt;/em&gt;, &lt;em&gt;177.8&lt;/em&gt;, &lt;em&gt;181.8&lt;/em&gt;, &lt;em&gt;175.9&lt;/em&gt;, &lt;em&gt;145.1&lt;/em&gt;, &lt;em&gt;177.8&lt;/em&gt;, &lt;em&gt;171.3&lt;/em&gt;, &lt;em&gt;176.9&lt;/em&gt;, &lt;em&gt;180.8&lt;/em&gt;, &lt;em&gt;189&lt;/em&gt;, &lt;em&gt;167.7&lt;/em&gt;, &lt;em&gt;188&lt;/em&gt;, &lt;em&gt;178.4&lt;/em&gt;, &lt;em&gt;185.4&lt;/em&gt;, &lt;em&gt;184.2&lt;/em&gt;, &lt;em&gt;182.2&lt;/em&gt;, &lt;em&gt;164.6&lt;/em&gt;, &lt;em&gt;174.1&lt;/em&gt;, &lt;em&gt;181.2&lt;/em&gt;, &lt;em&gt;165.5&lt;/em&gt;, &lt;em&gt;169.6&lt;/em&gt;, &lt;em&gt;180.8&lt;/em&gt;, &lt;em&gt;182.7&lt;/em&gt;, &lt;em&gt;179.6&lt;/em&gt;, &lt;em&gt;166.1&lt;/em&gt;, &lt;em&gt;164&lt;/em&gt;, &lt;em&gt;190.1&lt;/em&gt;, &lt;em&gt;177.6&lt;/em&gt;, &lt;em&gt;175.9&lt;/em&gt;, &lt;em&gt;173.8&lt;/em&gt;, &lt;em&gt;163.1&lt;/em&gt;, &lt;em&gt;181.1&lt;/em&gt;, &lt;em&gt;172.8&lt;/em&gt;, &lt;em&gt;173.2&lt;/em&gt;, &lt;em&gt;184.3&lt;/em&gt;, &lt;em&gt;183.2&lt;/em&gt;, &lt;em&gt;188.9&lt;/em&gt;, &lt;em&gt;170.2&lt;/em&gt;, &lt;em&gt;181.5&lt;/em&gt;, &lt;em&gt;188.9&lt;/em&gt;, &lt;em&gt;163.9&lt;/em&gt;, &lt;em&gt;166.4&lt;/em&gt;, &lt;em&gt;163.7&lt;/em&gt;, &lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Facing this series, it is hard (not to say impossible) for anyone to understand the data and have a clear view of the size of these adults in a reasonable amount of time. Descriptive statistics allow to summarize, and thus have a better overview of the data. Of course, by summarizing data through one or several measures, some information will inevitably be lost. However, in many cases it is generally better to lose some information but in return gain an overview.&lt;/p&gt;
&lt;p&gt;Descriptive statistics is often the first step and an important part in any statistical analysis. It allows to check the quality of the data by detecting potential &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt; (i.e., data points that appear to be separated from the rest of the data), collection or encoding errors. It also helps to “understand” the data and if well presented, descriptive statistics is already a good starting point for further analyses.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;location-versus-dispersion-measures&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Location versus dispersion measures&lt;/h1&gt;
&lt;p&gt;Several different measures (called statistics if we are analyzing a sample) are used to summarize the data. Some of them give an understanding about the &lt;strong&gt;location&lt;/strong&gt; of the data, others give and understanding about the &lt;strong&gt;dispersion&lt;/strong&gt; of the data. In practice, both types of measures are often used together in order to summarize the data in the most concise but complete way.&lt;/p&gt;
&lt;p&gt;We illustrate this point with the graph below, representing the height (in cm) of 100 persons divided into two groups (50 persons in each group):&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand_files/figure-html/unnamed-chunk-2-1.png&#34; width=&#34;100%&#34; style=&#34;display: block; margin: auto;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The black line corresponds to the mean. The mean height (in cm) is similar in both groups. However, it is clear that the dispersion of heights are very different in the two groups. For this reason, location or dispersion measures are often not enough if presented individually and it is a good practice to present several statistics from both types of measures.&lt;/p&gt;
&lt;p&gt;In the following sections, we detail the most common location and dispersion measures and illustrate them with examples. Note that for the sake of simplicity, we consider only series of values (i.e., univariate data) and not bivariate or multivariate data, and we do not consider the case of series grouped in classes.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;location&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Location&lt;/h1&gt;
&lt;p&gt;Location measures allow to see “where” the data are located, around which values. In other words, location measures give an understanding on &lt;strong&gt;what is the central tendency&lt;/strong&gt;, the “position” of the data as a whole. It includes the following statistics (others exist but we focus on the most common ones):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;minimum&lt;/li&gt;
&lt;li&gt;maximum&lt;/li&gt;
&lt;li&gt;mean&lt;/li&gt;
&lt;li&gt;median&lt;/li&gt;
&lt;li&gt;first quartile&lt;/li&gt;
&lt;li&gt;third quartile&lt;/li&gt;
&lt;li&gt;mode&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We detail and compute by hand each of them in the following sections.&lt;/p&gt;
&lt;div id=&#34;minimum-and-maximum&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Minimum and maximum&lt;/h2&gt;
&lt;p&gt;Minimum (&lt;span class=&#34;math inline&#34;&gt;\(min\)&lt;/span&gt;) and maximum (&lt;span class=&#34;math inline&#34;&gt;\(max\)&lt;/span&gt;) are simply the lowest and largest values, respectively. Given the height (in cm) of a sample of 6 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;188.7&lt;/em&gt;, &lt;em&gt;169.4&lt;/em&gt;, &lt;em&gt;178.6&lt;/em&gt;, &lt;em&gt;181.3&lt;/em&gt;, &lt;em&gt;179&lt;/em&gt; and &lt;em&gt;173.9&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The minimum is 169.4 cm and the maximum is 188.7 cm. These two basic statistics give a clear idea about the size of the smallest and tallest of these 6 adults.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;mean&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Mean&lt;/h2&gt;
&lt;p&gt;The mean, also known as average, is probably the most common statistics. It gives an idea on what is the average value, that is, the central value of the data or in other words the center of gravity:&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;div style=&#34;text-align:center&#34;&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand_files/mean.png&#34; alt=&#34;Mean. Source: LFSAB1105 at UCLouvain&#34; style=&#34;width: 80%;&#34;&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The mean is found by summing all values and dividing the total by the number of observations (denoted &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt;):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[mean = \bar{x} = \frac{\text{sum of all values}}{\text{number of values}} = \frac{1}{n}\sum^{n}_{i = 1} x_i\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Given our sample of 6 adults presented above, the mean is:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\bar{x} = \frac{188.7 + 169.4 + 178.6}{6}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[\frac{+ 181.3 + 179 + 173.9}{6}\\ = 178.4833\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In conclusion, the mean size, that is, the average size of our sample of 6 adults is 178.48 cm (rounded to 2 decimals).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;median&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Median&lt;/h2&gt;
&lt;p&gt;The median is another measure of location so it also gives an idea about the central tendency of the data. The interpretation of the median is that there are as many observations below as above the median. In other words, 50% of the observations lie below the median, and 50% of the observations lie above the median. Below a visual representation of the median:&lt;/p&gt;
&lt;div style=&#34;text-align: center;&#34;&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand_files/median.png&#34; alt=&#34;Median. Source: LFSAB1105 at UCLouvain&#34; style=&#34;width: 80%;&#34;&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The easiest way to compute the median is by first sorting the data from lowest to highest (i.e., in ascending order) then take the middle point as the median. From the sorted values, for an odd number of observations, the middle point is easy to find: it is the value with as many observations below as above. Still from the sorted values, for an even number of observations, the middle point is exactly between the two middle values. Formally, after sorting, the median is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;if &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; (number of observations) is odd: &lt;span class=&#34;math display&#34;&gt;\[med(x) = x_{\frac{n+1}{2}}\]&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;if &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is even: &lt;span class=&#34;math display&#34;&gt;\[med(x) = \frac{1}{2}\big(x_{\frac{n}{2}} + x_{\frac{n}{2} + 1}\big)\]&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;where the subscript of &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt; denotes the numbering of the sorted data. The formulas look harder than they really are, so let’s see with two concrete examples.&lt;/p&gt;
&lt;div id=&#34;odd-number-of-observations&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Odd number of observations&lt;/h3&gt;
&lt;p&gt;Given the height of a sample of 7 adults taken from the 100 adults presented in the introduction:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;188.9&lt;/em&gt;, &lt;em&gt;163.9&lt;/em&gt;, &lt;em&gt;166.4&lt;/em&gt;, &lt;em&gt;163.7&lt;/em&gt;, &lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;We first sort the order from lowest to highest:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;163.7&lt;/em&gt;, &lt;em&gt;163.9&lt;/em&gt;, &lt;em&gt;166.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt;, &lt;em&gt;181.5&lt;/em&gt; and &lt;em&gt;188.9&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Given that the number of observations &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is odd (since &lt;span class=&#34;math inline&#34;&gt;\(n = 7\)&lt;/span&gt;), the median is&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[med(x) = x_\frac{7 + 1}{2} = x_4\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;So we take the fourth value from the sorted values, which corresponds to 166.4. In conclusion, the median size of these 7 adults is 166.4 cm. As you can see, there are 3 observations below 166.4 and 3 observations above 166.4 cm.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;even-number-of-observations&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Even number of observations&lt;/h3&gt;
&lt;p&gt;Now let’s see when the number of observations is even, which is slightly more complicated than when the number of observations is odd. Given the height of a sample of 6 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;188.7&lt;/em&gt;, &lt;em&gt;169.4&lt;/em&gt;, &lt;em&gt;178.6&lt;/em&gt;, &lt;em&gt;181.3&lt;/em&gt;, &lt;em&gt;179&lt;/em&gt; and &lt;em&gt;173.9&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;We sort the values in ascending order:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;169.4&lt;/em&gt;, &lt;em&gt;173.9&lt;/em&gt;, &lt;em&gt;178.6&lt;/em&gt;, &lt;em&gt;179&lt;/em&gt;, &lt;em&gt;181.3&lt;/em&gt; and &lt;em&gt;188.7&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Given that the number of observations &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; is even (since &lt;span class=&#34;math inline&#34;&gt;\(n = 6\)&lt;/span&gt;), the median is&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[med(x) = \frac{1}{2}\big(x_{\frac{6}{2}} + x_{\frac{6}{2} + 1}\big) = \frac{1}{2}\big(x_{3} + x_{4}\big)\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;So we sum the third and fourth values from the sorted values and divide the total by 2 (which is equivalent than taking the mean of these two middle values):&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\frac{1}{2}(178.6 + 179) = 178.8\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In conclusion, the median size of these 6 adults is 178.8 cm. Again, remark that there are as many observations below as above 178.8 cm.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;mean-vs.-median&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Mean vs. median&lt;/h2&gt;
&lt;p&gt;Although the mean and median are often relatively close to each other (in particular when the distribution is symmetric) they should not be confused since they both have advantages and disadvantages in different contexts. Besides the fact that almost everyone knows (or at least have heard about) the mean, it has the advantage that it gives a unique picture for each different series of data. However, it has the disadvantage that the mean is sensible to &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt; (i.e., extreme values). On the other hand, the advantage of the median is that it is resistant to outliers and the inconvenient is that it may be the exact same value for very different series of data (so not unique to the data).&lt;/p&gt;
&lt;p&gt;To illustrate the “sensible to outlier” argument, consider 3 friends in a bar comparing their salaries. Their salaries are &lt;em&gt;1800&lt;/em&gt;, &lt;em&gt;2000&lt;/em&gt; and &lt;em&gt;2100&lt;/em&gt;€, for an average (mean) salary of &lt;em&gt;1967&lt;/em&gt;€. A friend of them (who happens to be friend with Bill Gates as well) joins them in the bar. Their salaries are now &lt;em&gt;1800&lt;/em&gt;, &lt;em&gt;2000&lt;/em&gt;, &lt;em&gt;2100&lt;/em&gt; and &lt;em&gt;1000000&lt;/em&gt;€. The average salary of the 4 friends is now &lt;em&gt;251475&lt;/em&gt;€, compared to &lt;em&gt;1967&lt;/em&gt;€ without the rich friend. Although it is statistically correct to say that the mean salary of the 4 friends is &lt;em&gt;251475&lt;/em&gt;€, you will concede that this measure does not represent a fair image of the salaries of the 4 friends, as 3 of them earn much less than the mean salary. As we have just seen, the mean is sensible to outliers. (&lt;em&gt;Note:&lt;/em&gt; this example also shows how a large majority of citizens earn less than the mean salary reported in the news. For the french-speaking readers, see this &lt;a href=&#34;https://www.youtube.com/watch?v=uIx2xvdwIIo&#34;&gt;video&lt;/a&gt; for more information.)&lt;/p&gt;
&lt;p&gt;On the other hand, if we report the medians, we see that the median salary of the 3 first friends is &lt;em&gt;2000&lt;/em&gt;€, and the median salary of the 4 friends is &lt;em&gt;2050&lt;/em&gt;€. As you can see with this example, the median is not sensible to outliers and for series with such extreme value(s), the median is more appropriate compared to the mean as it often gives a better representation of the data.&lt;/p&gt;
&lt;p&gt;Given the previous example, one may then choose to always use the median instead of the mean. However, the median has it own inconvenient which the mean does not have: the median is less unique and less specific to its underlying data than the mean. Consider the following data, representing the grades of 5 students taking a statistics and economics exam:&lt;/p&gt;
&lt;table style=&#34;width:51%;&#34;&gt;
&lt;colgroup&gt;
&lt;col width=&#34;16%&#34; /&gt;
&lt;col width=&#34;16%&#34; /&gt;
&lt;col width=&#34;18%&#34; /&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th align=&#34;center&#34;&gt;studentID&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;economics&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;statistics&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;1&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;2&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;7&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;3&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td align=&#34;center&#34;&gt;4&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;18&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;10&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td align=&#34;center&#34;&gt;5&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;20&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;11&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;br&gt;
The median of the grades is the same in economics and statistics (median = &lt;em&gt;10&lt;/em&gt;). Therefore, had we computed only the medians, we could have concluded that the students performed as well in economics as in statistics. However, although the medians are exactly the same for both classes, it is clear that students performed better in economics than in statistics (compare both grades for each student to see for yourself). In fact, the mean of the grades in economics is &lt;em&gt;13.6&lt;/em&gt; and the mean of the grades in statistics is &lt;em&gt;8.6&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;What we have just shown here is that the median is based only on one single value, the middle value, or on the two middle values if there are an even number of observations, while the mean is based on all values (and thus includes more information). The median is therefore not sensible to outliers, but it is also not unique (i.e., not specific) to different series of data, whereas the mean is much more likely to be different and unique for different series of data. This difference in terms of specificity and uniqueness between the two measures may make the mean more useful for data with no outlier.&lt;/p&gt;
&lt;p&gt;In conclusion, depending on the context and the data, it is often more interesting to report the mean or the median, or both. As a last remark regarding the comparison between the two most important location measures, note that when the mean and median are equal, the distribution of your data can often be considered to follow a &lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution&lt;/a&gt; (also referred as a Gaussian distribution).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;st-and-3rd-quartiles&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;&lt;span class=&#34;math inline&#34;&gt;\(1^{st}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(3^{rd}\)&lt;/span&gt; quartiles&lt;/h2&gt;
&lt;p&gt;The first and third quartiles are similar to the median in the sense that they also divide the observations into two parts, except that these parts are not equal. Remind that the median divides the data into two equal parts (with 50% of the observations below and 50% above the median).&lt;/p&gt;
&lt;p&gt;The first quartile cuts the observations such that there are 25% of the observations &lt;strong&gt;below&lt;/strong&gt; and thus 75% &lt;strong&gt;above&lt;/strong&gt; the first quartile. The third quartile, as you have guessed by now, represents the value with 75% of the observations below it and thus 25% of the observations above it. There exists several methods to compute the first and third quartile (which sometimes give slight differences, R for instance uses a different method), but here is I believe the easiest one when computing these statistics by hand:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;sort the data in ascending order&lt;/li&gt;
&lt;li&gt;compute &lt;span class=&#34;math inline&#34;&gt;\(0.25 \cdot n\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(0.75 \cdot n\)&lt;/span&gt; (i.e., 0.25 and 0.75 times the number of observations)&lt;/li&gt;
&lt;li&gt;round up these two numbers to the next whole number&lt;/li&gt;
&lt;li&gt;these two numbers represent the rank of the first and third quartile (in the sorted series), respectively&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The steps are the same for both an odd and even number of observations. Here is an example with the following series, representing the height in cm of 9 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;170.2&lt;/em&gt;, &lt;em&gt;181.5&lt;/em&gt;, &lt;em&gt;188.9&lt;/em&gt;, &lt;em&gt;163.9&lt;/em&gt;, &lt;em&gt;166.4&lt;/em&gt;, &lt;em&gt;163.7&lt;/em&gt;, &lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;We first order from lowest to highest:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;163.7&lt;/em&gt;, &lt;em&gt;163.9&lt;/em&gt;, &lt;em&gt;166.4&lt;/em&gt;, &lt;em&gt;170.2&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt;, &lt;em&gt;181.5&lt;/em&gt;, &lt;em&gt;181.5&lt;/em&gt; and &lt;em&gt;188.9&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;There are 9 observations so &lt;span class=&#34;math display&#34;&gt;\[0.25 \cdot 9 = 2.25\]&lt;/span&gt; and &lt;span class=&#34;math display&#34;&gt;\[0.75 \cdot 9 = 6.75\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Rounding up to the whole number gives 3 and 7, which represent the rank of the first and third quartiles, respectively. Therefore, the first quartile is 163.9 cm and the third quartile is 181.5 cm.&lt;/p&gt;
&lt;p&gt;In conclusion, 25% of adults are less than 163.9 cm tall (and thus 75% of them are more than 163.9 cm tall), while 75% of adults are less than 181.5 cm tall (and thus 25% of them are more than 181.5 cm tall).&lt;/p&gt;
&lt;div id=&#34;q_0.25-q_0.75-and-q_0.5&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;&lt;span class=&#34;math inline&#34;&gt;\(q_{0.25}\)&lt;/span&gt;, &lt;span class=&#34;math inline&#34;&gt;\(q_{0.75}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(q_{0.5}\)&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Note that the first quartile is denoted &lt;span class=&#34;math inline&#34;&gt;\(q_{0.25}\)&lt;/span&gt; and the third quartile is denoted &lt;span class=&#34;math inline&#34;&gt;\(q_{0.75}\)&lt;/span&gt; (where &lt;span class=&#34;math inline&#34;&gt;\(q\)&lt;/span&gt; stands for quartile). As you can see, the median is actually the second quartile and for this reason it is also sometimes denoted &lt;span class=&#34;math inline&#34;&gt;\(q_{0.5}\)&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;a-note-on-deciles-and-percentiles&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;A note on deciles and percentiles&lt;/h3&gt;
&lt;p&gt;Deciles and percentiles are similar to quartiles except that they cuts the data in 10 and 100 equal parts. For instance, the &lt;span class=&#34;math inline&#34;&gt;\(4^{th}\)&lt;/span&gt; decile (&lt;span class=&#34;math inline&#34;&gt;\(q_{0.4}\)&lt;/span&gt;) is the value such that there are 40% of the observations below it and thus 60% of the observations above it.&lt;/p&gt;
&lt;p&gt;Percentiles follow the same logic. For example, the &lt;span class=&#34;math inline&#34;&gt;\(98^{th}\)&lt;/span&gt; percentile (&lt;span class=&#34;math inline&#34;&gt;\(q_{0.98}\)&lt;/span&gt;, also sometimes denoted &lt;span class=&#34;math inline&#34;&gt;\(P98\)&lt;/span&gt;) is the value such that there are 98% of the observations below it and thus 2% of the observations above it. Percentiles are often used for the weight and height of babies, giving precise information to the parents about where their child stands compared to other children of the same age.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;mode&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Mode&lt;/h2&gt;
&lt;p&gt;The mode of a series is the value that appears most often. In other words, it is the value that has the highest number of occurrences.&lt;/p&gt;
&lt;p&gt;Unlike some descriptive statistics that can only be computed for quantitative variables (the mean for instance), the mode can be computed for quantitative &lt;strong&gt;and&lt;/strong&gt; qualitative variables (see a recap of the different &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/&#34;&gt;types of variables&lt;/a&gt; if you do not remember the difference).&lt;/p&gt;
&lt;div id=&#34;quantitative-variables&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Quantitative variables&lt;/h3&gt;
&lt;p&gt;Given the height of 9 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;170&lt;/em&gt;, &lt;em&gt;168&lt;/em&gt;, &lt;em&gt;171&lt;/em&gt;, &lt;em&gt;170&lt;/em&gt;, &lt;em&gt;182&lt;/em&gt;, &lt;em&gt;165&lt;/em&gt;, &lt;em&gt;170&lt;/em&gt;, &lt;em&gt;189&lt;/em&gt; and &lt;em&gt;167&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The mode is 170 because it is the most common value with 3 occurrences. All other values appear only once.&lt;/p&gt;
&lt;p&gt;Note that it is possible that a series has no mode or more than one mode:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the series &lt;em&gt;4&lt;/em&gt;, &lt;em&gt;7&lt;/em&gt;, &lt;em&gt;2&lt;/em&gt; and &lt;em&gt;10&lt;/em&gt; has no mode,&lt;/li&gt;
&lt;li&gt;the series &lt;em&gt;4&lt;/em&gt;, &lt;em&gt;2&lt;/em&gt;, &lt;em&gt;2&lt;/em&gt;, &lt;em&gt;8&lt;/em&gt;, &lt;em&gt;11&lt;/em&gt; and &lt;em&gt;11&lt;/em&gt; has two modes.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Data with two modes are often called bimodal and data with more than two modes are often called multimodal, as opposed to series with one mode which are referred as unimodal.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;qualitative-variables&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Qualitative variables&lt;/h3&gt;
&lt;p&gt;Given the eye color of the 9 adults presented above:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;brown&lt;/em&gt;, &lt;em&gt;brown&lt;/em&gt;, &lt;em&gt;brown&lt;/em&gt;, &lt;em&gt;brown&lt;/em&gt;, &lt;em&gt;blue&lt;/em&gt;, &lt;em&gt;blue&lt;/em&gt;, &lt;em&gt;blue&lt;/em&gt;, &lt;em&gt;brown&lt;/em&gt; and &lt;em&gt;green&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Brown is the most frequent color, so the mode is brown.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;dispersion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Dispersion&lt;/h1&gt;
&lt;p&gt;All previous descriptive statistics helps to get a sense of the location and position of the data. We now present the most common dispersion measures, which help to get a sense of the &lt;strong&gt;dispersion and the variability&lt;/strong&gt; of the data (to which extent a distribution is squeezed or stretched):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;range&lt;/li&gt;
&lt;li&gt;standard deviation&lt;/li&gt;
&lt;li&gt;variance&lt;/li&gt;
&lt;li&gt;interquartile range&lt;/li&gt;
&lt;li&gt;coefficient of variation&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;As for location measures, we detail and compute by hand each of these statistics one by one.&lt;/p&gt;
&lt;div id=&#34;range&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Range&lt;/h2&gt;
&lt;p&gt;The range is the difference between the maximum and the minimum value:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[range = max - min\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Given the height (in cm) of our sample of 6 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;188.7&lt;/em&gt;, &lt;em&gt;169.4&lt;/em&gt;, &lt;em&gt;178.6&lt;/em&gt;, &lt;em&gt;181.3&lt;/em&gt;, &lt;em&gt;179&lt;/em&gt; and &lt;em&gt;173.9&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The range is 188.7 &lt;span class=&#34;math inline&#34;&gt;\(-\)&lt;/span&gt; 169.4 &lt;span class=&#34;math inline&#34;&gt;\(=\)&lt;/span&gt; 19.3 cm. The advantage of the range is that it is extremely easy to compute it and it gives a precise idea about the “length” of the data. The disadvantage is that it relies on the two most extreme values only, so it is highly sensible to &lt;a href=&#34;https://statsandr.com/blog/outliers-detection-in-r/&#34;&gt;outliers&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;standard-deviation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Standard deviation&lt;/h2&gt;
&lt;p&gt;The standard deviation is the most common dispersion measure in statistics. Like the mean for the location measures, if we have to present one statistics which summarizes the spread of the data, it is usually the standard deviation.&lt;/p&gt;
&lt;p&gt;As its name suggests, the standard deviation tells what is the “normal” deviation of the data. It actually computes the &lt;strong&gt;mean deviation from the global mean&lt;/strong&gt;. The larger the standard deviation, the more scattered the data are. On the contrary, the smaller the standard deviation, the more the data are centered around the mean. Below a visual representation of the standard deviation:&lt;/p&gt;
&lt;div style=&#34;text-align: center;&#34;&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand_files/standard-deviation.png&#34; alt=&#34;Standard deviation. Source: LFSAB1105 at UCLouvain&#34; style=&#34;width: 80%;&#34;&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The standard deviation is a bit more complex than the previous statistics in the sense that there are two formulas depending on whether we face a sample or a population. A population includes all members from a specified group, all possible outcomes or measurements that are of interest. A sample consists of some observations drawn from the population, so a part or a subset of the population. For instance, the population may be “&lt;strong&gt;all&lt;/strong&gt; people living in Belgium” and the sample may be “&lt;strong&gt;some&lt;/strong&gt; people living in Belgium”. Read this article on &lt;a href=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/&#34;&gt;the difference between population and sample&lt;/a&gt; if you want to learn more.&lt;/p&gt;
&lt;div id=&#34;standard-deviation-for-a-population&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Standard deviation for a population&lt;/h3&gt;
&lt;p&gt;The standard deviation for a population, denoted &lt;span class=&#34;math inline&#34;&gt;\(\sigma\)&lt;/span&gt;, is:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\sigma = \sqrt{\frac{1}{n}\sum^n_{i = 1}(x_i - \mu)^2}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;As you can see from the formula, the standard deviation is actually the mean deviation of the data from the global mean &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt;. Note the square for the difference between the observations (&lt;span class=&#34;math inline&#34;&gt;\(x_i\)&lt;/span&gt;) and the mean (&lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt;) to avoid that negative differences are compensated by positive differences.&lt;/p&gt;
&lt;p&gt;For the sake of easiness, imagine a population of only 3 adults (the steps are the same with a large population, the computation is just longer). Below their heights (in cm):&lt;/p&gt;
&lt;p&gt;&lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The mean is 172.6 (rounded to 1 decimal). The standard deviation is thus:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\sigma = \sqrt{\frac{1}{3} \big[(160.4 - 172.6)^2 \\ + (175.8 - 172.6)^2 \\ + (181.5 - 172.6)^2 \big]}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[\sigma = 8.91\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In conclusion, the standard deviation for the heights of these 3 adults is 8.91 cm. This means that, on average, the height of the adults in this population deviates from the mean by 8.91 cm.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;standard-deviation-for-a-sample&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Standard deviation for a sample&lt;/h3&gt;
&lt;p&gt;The standard deviation for a sample is similar to the standard deviation for a population except that we divide by &lt;span class=&#34;math inline&#34;&gt;\(n -1\)&lt;/span&gt; instead of &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; and it is denoted &lt;span class=&#34;math inline&#34;&gt;\(s\)&lt;/span&gt;:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[s = \sqrt{\frac{1}{n-1}\sum^n_{i = 1}(x_i - \bar{x})^2}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Imagine now that the 3 adults presented in the previous section is a sample instead of a population:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The mean is still 172.6 (rounded to 1 decimal) since the mean is the same whether it is a population or a sample. The standard deviation is now:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[s = \sqrt{\frac{1}{3 - 1} \big[(160.4 - 172.6)^2 \\ + (175.8 - 172.6)^2 \\ + (181.5 - 172.6)^2 \big]}\]&lt;/span&gt;
&lt;span class=&#34;math display&#34;&gt;\[s = 10.92\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In conclusion, the standard deviation for the heights of these 3 adults is 10.92 cm. The interpretation is the same than for a population.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;variance&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Variance&lt;/h2&gt;
&lt;p&gt;The variance is simply the square of the standard deviation. Put it another way, the standard deviation is the square root of the variance. We also distinguish between the variance for a population and for a sample in the next sections.&lt;/p&gt;
&lt;div id=&#34;variance-for-a-population&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Variance for a population&lt;/h3&gt;
&lt;p&gt;The variance for a population, denoted &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2\)&lt;/span&gt;, is:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\sigma^2 = \frac{1}{n}\sum^n_{i = 1}(x_i - \mu)^2\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;As you can see, the formula for variance is the same than for standard deviation, except that the square root is removed for the variance. Remember the heights of our population of 3 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The standard deviation was 8.91 cm, so the variance of the height of these adults is &lt;span class=&#34;math inline&#34;&gt;\(8.91^2 = 79.39\)&lt;/span&gt; &lt;span class=&#34;math inline&#34;&gt;\(cm^2\)&lt;/span&gt; (see below why the unit of a variance is &lt;span class=&#34;math inline&#34;&gt;\(unit^2\)&lt;/span&gt;).&lt;/p&gt;
&lt;p&gt;If you did not know the standard deviation of the population and needed to compute the variance of the population by hand, here is how:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[\sigma^2 = \frac{1}{3} \big[(160.4 - 172.6)^2 \\ + (175.8 - 172.6)^2 \\ + (181.5 - 172.6)^2 \big] \\ = 79.43\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;(The difference with the above result is due to rounding.)&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;variance-for-a-sample&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Variance for a sample&lt;/h3&gt;
&lt;p&gt;Again, the variance for a sample is similar to the variance for a population except that we divide by &lt;span class=&#34;math inline&#34;&gt;\(n - 1\)&lt;/span&gt; instead of &lt;span class=&#34;math inline&#34;&gt;\(n\)&lt;/span&gt; and it is denoted &lt;span class=&#34;math inline&#34;&gt;\(s^2\)&lt;/span&gt;:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[s^2 = \frac{1}{n-1}\sum^n_{i = 1}(x_i - \bar{x})^2\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Imagine again that the 3 adults in the previous section is a sample instead of a population:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The standard deviation for this sample was 10.92 cm, so the variance of the height of these adults is &lt;span class=&#34;math inline&#34;&gt;\(10.92^2 = 119.25\)&lt;/span&gt; &lt;span class=&#34;math inline&#34;&gt;\(cm^2\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;If you did not know the standard deviation of the sample and needed to compute the variance of the sample by hand, here is how:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[s^2 = \frac{1}{3 - 1} \big[(160.4 - 172.6)^2 \\ + (175.8 - 172.6)^2 \\ + (181.5 - 172.6)^2 \big] \\ = 119.15\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;(The difference with the above result is due to rounding.)&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;standard-deviation-vs.-variance&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Standard deviation vs. variance&lt;/h2&gt;
&lt;p&gt;Standard deviation and variance are often used interchangeably and both quantify the spread of a given dataset by measuring how far the observations are from their mean. However, the standard deviation can be more easily interpreted because the unit for the standard deviation is the same than the unit of measurement of the data (while it is the &lt;span class=&#34;math inline&#34;&gt;\(unit^2\)&lt;/span&gt; for the variance).&lt;/p&gt;
&lt;p&gt;Following our example of adult heights in cm, the standard deviation is measured in cm while the variance is measured in &lt;span class=&#34;math inline&#34;&gt;\(cm^2\)&lt;/span&gt;. The fact that the standard deviation keeps the same unit than the initial unit of measurement makes it more interpretable and thus more often used in practice.&lt;/p&gt;
&lt;div id=&#34;notations&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Notations&lt;/h3&gt;
&lt;p&gt;For completeness, below a table showing the different notations for variance and standard deviation in case of population and sample:&lt;/p&gt;
&lt;center&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th align=&#34;center&#34;&gt;Population&lt;/th&gt;
&lt;th align=&#34;right&#34;&gt;Sample&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Standard deviation&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(\sigma\)&lt;/span&gt;&lt;/td&gt;
&lt;td align=&#34;right&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(s\)&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Variance&lt;/td&gt;
&lt;td align=&#34;center&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(\sigma^2\)&lt;/span&gt;&lt;/td&gt;
&lt;td align=&#34;right&#34;&gt;&lt;span class=&#34;math inline&#34;&gt;\(s^2\)&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;interquartile-range&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Interquartile range&lt;/h2&gt;
&lt;p&gt;Remember the first &lt;span class=&#34;math inline&#34;&gt;\(q_{0.25}\)&lt;/span&gt; and third quartile &lt;span class=&#34;math inline&#34;&gt;\(q_{0.75}\)&lt;/span&gt; presented earlier (see this &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/#st-and-3rd-quartiles&#34;&gt;section&lt;/a&gt;). The interquartile range is another measure of dispersion of the data, using the quartiles. It is the difference between the third and first quartile:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[IQR = q_{0.75} - q_{0.25}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Considering the height of the 9 adults presented in the section about the first and third quartile:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;170.2&lt;/em&gt;, &lt;em&gt;181.5&lt;/em&gt;, &lt;em&gt;188.9&lt;/em&gt;, &lt;em&gt;163.9&lt;/em&gt;, &lt;em&gt;166.4&lt;/em&gt;, &lt;em&gt;163.7&lt;/em&gt;, &lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The first quartile was 163.9 cm and the third quartile was 181.5 cm. The IQR is thus:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[IQR = 181.5 - 163.9 = 17.6\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In conclusion, the interquartile range is 17.6 cm. The interquartile range is actually the range (since it is the difference between a higher and a lower value) of the middle data. The graph below may help to understand better the IQR and the quartiles:&lt;/p&gt;
&lt;div style=&#34;text-align: center;&#34;&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand_files/IQR-quartiles.png&#34; alt=&#34;IQR, first and third quartile. Source: LFSAB1105 at UCLouvain&#34; style=&#34;width: 80%;&#34;&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;coefficient-of-variation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Coefficient of variation&lt;/h2&gt;
&lt;p&gt;The last dispersion measure is the coefficient of variation. The coefficient of variation, denoted &lt;span class=&#34;math inline&#34;&gt;\(CV\)&lt;/span&gt;, is the standard deviation divided by the mean. Formally:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[CV = \frac{s}{\bar{x}}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Consider the height of a sample of 4 adults:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;163.7&lt;/em&gt;, &lt;em&gt;160.4&lt;/em&gt;, &lt;em&gt;175.8&lt;/em&gt; and &lt;em&gt;181.5&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The mean is &lt;span class=&#34;math inline&#34;&gt;\(\bar{x} =\)&lt;/span&gt; 170.35 cm and the standard deviation is &lt;span class=&#34;math inline&#34;&gt;\(s =\)&lt;/span&gt; 9.95 cm. (Find the same values as an exercise!) The coefficient of variation is&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[CV = \frac{9.95 \text{ cm}}{170.35 \text{ cm}} = 0.058 = 5.8\%\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In conclusion, the coefficient of variation is 5.8%. Note that, as a rule of thumb, a coefficient of variation greater than 15% usually means that the data are &lt;strong&gt;heterogeneous&lt;/strong&gt; while a coefficient of variation equal to or less than 15% means that the data are &lt;strong&gt;homogeneous&lt;/strong&gt;. Given that the coefficient of variation equals 5.8% in this case, we can conclude that these 4 adults are homogeneous in terms of height.&lt;/p&gt;
&lt;p&gt;Note that the coefficient of variation for a population follows the same formula, except that notations for the mean and the standard deviation differ:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[CV = \frac{\sigma}{\mu}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The interpretation is also the same as for a sample.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;coefficient-of-variation-vs.-standard-deviation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Coefficient of variation vs. standard deviation&lt;/h2&gt;
&lt;p&gt;Although the coefficient of variation is rather unknown to the public, it is, in fact, worth presenting when making descriptive statistics.&lt;/p&gt;
&lt;p&gt;The standard deviation should always be understood in the context of the mean of the data and is dependent on its unit. The standard deviation has the advantage that it tells by how far on average the data is from the mean in terms of unit in which the data has been measured. Standard deviation is useful when considering variables with same units and approximately same means. However, standard deviation becomes less useful when comparing variables with different units or widely different means. For instance, a variable with a standard deviation of 10 cm cannot be compared to a variable with a standard deviation of 12€ to conclude which one of the two is the most dispersed.&lt;/p&gt;
&lt;p&gt;The coefficient of variation is a ratio of two statistics with the same units. It has thus no unit and is independent of the unit in which the data has been measured. Being unit-free, coefficients of variation computed on datasets or variables with different units or widely different means can be compared to conclude, in fine, which data or variables is more (or less) dispersed. For instance, consider a sample of 10 women with their heights in cm and their salaries in €. We cannot compare the dispersion of their weights with the dispersion of their salaries because it is not measured on the same unit/scale. Now suppose that the coefficients of variation are 0.032 and 0.061 respectively for the height and the salary. Based on that, we can conclude that, relative to their respective average, their salaries vary more than their heights for these women. This is the case because the coefficient of variation is larger for the salary compared to the coefficient variation for the height, and a coefficient of variation has no unit (it is a ratio).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Remember that descriptive statistics are useful to describe and present a series of observations in a concise and informative way. There are two families of descriptive statistics: location and dispersion measures. Location measures give information about the position of the data, whereas dispersion measures give information about the variability of the data.&lt;/p&gt;
&lt;p&gt;We showed how to compute the most common descriptive statistics by hand with concrete examples. We also discussed differences between some measures and when it is more appropriate to use one or the other depending on the context and the data at hand.&lt;/p&gt;
&lt;p&gt;This concludes a relatively long article, thanks for reading! If you would like to learn how to compute these measures in R, read the article “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;Descriptive statistics in R&lt;/a&gt;”. A book I recommend for further reading is “&lt;a href=&#34;https://capitaloneshopping.com/p/statistics/VWP5CXD9KP&#34; target=&#34;_blank&#34;&gt;The Art of Statistics&lt;/a&gt;” by David Spiegelhalter. It is a great book for beginners in statistics and covers a wide range of topics.&lt;/p&gt;
&lt;p&gt;As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;This image and the following ones are taken from the LFSAB1105 course syllabus at UCLouvain.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>What is the difference between population and sample?</title>
      <link>https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/</link>
      <pubDate>Sat, 18 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/what-is-the-difference-between-population-and-sample/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#sample-vs.-population&#34; id=&#34;toc-sample-vs.-population&#34;&gt;Sample vs. population&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#why-a-sample&#34; id=&#34;toc-why-a-sample&#34;&gt;Why a sample?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#representative-sample&#34; id=&#34;toc-representative-sample&#34;&gt;Representative sample&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#paired-samples&#34; id=&#34;toc-paired-samples&#34;&gt;Paired samples&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample_files/difference-between-population-and-sample.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;People often fail to properly distinguish between population and sample. It is however essential in any statistical analysis, starting from &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics&lt;/a&gt; with different formulas for variance and standard deviation depending on whether we face a sample or a population.&lt;/p&gt;
&lt;p&gt;Moreover, the branch of statistics called &lt;a href=&#34;https://statsandr.com/blog/a-shiny-app-for-inferential-statistics-by-hand/&#34;&gt;inferential statistics&lt;/a&gt; is often defined as the science of drawing conclusions about a population from observations made on a representative sample of that population. It is therefore crucial to properly distinguish between the two concepts. So, what exactly is the difference between population and sample?&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;sample-vs.-population&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Sample vs. population&lt;/h1&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/what-is-the-difference-between-population-and-sample_files/population-sample.png&#34; alt=&#34;&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;Population versus sample. Source: towardsdatascience.com&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;A &lt;strong&gt;population&lt;/strong&gt; includes &lt;strong&gt;all members&lt;/strong&gt; from a specified group, all possible outcomes or measurements that are of interest. The exact population will depend on the scope of the study. For example, say you would like to know whether there is an association between job performance and the amount of home working hours per week in the specific case of Belgian data scientists. In this case, the population might be Belgian data scientists. However, if the scope of the study is more narrow (e.g., the study focuses on french-speaking Belgian data scientists who live at least 30km away from their workplace), then the population will be more specific and include only workers who meet the criteria. The point is that the population should only include people to whom the results will apply.&lt;/p&gt;
&lt;p&gt;A &lt;strong&gt;sample&lt;/strong&gt; consists of some observations drawn from the population, so a part or a &lt;strong&gt;subset of the population&lt;/strong&gt;. The sample is the group of elements who actually participated in the study.&lt;/p&gt;
&lt;p&gt;Members and elements are defined in the broad sense of the term. It may be human. For instance, the population may be “&lt;strong&gt;all&lt;/strong&gt; people living in Belgium” and the sample may be “&lt;strong&gt;some&lt;/strong&gt; people living in Belgium”. It can be anything else too. Say you are testing the effect of a new fertilizer on crop yield. All the crop fields represent your population, whereas the 10 crop fields you tested correspond to your sample. Since a sample is a subset of a population, a sample is always smaller than the population.&lt;a href=&#34;#fn1&#34; class=&#34;footnote-ref&#34; id=&#34;fnref1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; Note that, a population must not necessarily be large. It might be the case that you study such a narrow population (e.g., first-year male bachelor students from your university who passed the statistics exam in June and for whom their parents have been divorced for more than 5 years), that the size of the population is actually rather small.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;why-a-sample&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Why a sample?&lt;/h1&gt;
&lt;p&gt;As mentioned at the beginning of this article, one of the main concern in statistics is being able to draw conclusions about a population from a representative sample. Why using a sample of the population and not directly the population? In general it is almost always impossible to carry out measurements for the entire study population because:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the population is too large. Example: the population of pregnant women. If we want to take measurements on all pregnant women in the world, it will most likely either take too long or cost too much&lt;/li&gt;
&lt;li&gt;the population is virtual. In this case “virtual” population is understood as a “hypothetical” population: it is unlimited in size. Example: for an experimental study, we focus on men with prostate cancer treated with a new treatment. We do not know how many people will be treated, so the population varies, is infinite and uncountable at the present time, and therefore virtual&lt;/li&gt;
&lt;li&gt;the population is not easily reachable. Example: the population of homeless persons in Belgium&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For these reasons, measurements are made on a subgroup of observations from the population, i.e., on a sample of our population. These measures are then used to draw conclusions about the population of interest. With an appropriate methodology and a sufficiently large sample size, the results obtained on a sample are often almost as accurate as those that would be obtained on the entire population.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;representative-sample&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Representative sample&lt;/h1&gt;
&lt;p&gt;Of course, the sample must be selected to be representative of the population under study. If participants are included in a study on a voluntary basis, there is a serious concern that the resulting sample may not be representative of the population. It may be the case that volunteers are different in terms of the parameter&lt;a href=&#34;#fn2&#34; class=&#34;footnote-ref&#34; id=&#34;fnref2&#34;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt; of interest, leading to a selection bias. Another selection bias can occur when, for instance, a researcher collects citizens’ wage, by the means of internet. It might be the case that people having access to internet have different wages than people who do not have access.&lt;/p&gt;
&lt;p&gt;The gold standard to select a sample representative of the population under study is by selecting a &lt;strong&gt;random&lt;/strong&gt; sample. A random sample is a sample selected at random from the population so that each member of the population has an equal chance of being selected. A random sample is usually an unbiased sample, that is, a sample whose randomness is not in doubt.&lt;/p&gt;
&lt;p&gt;In some situations or domains (e.g., in medicine, psychology, etc.) it is complicated or even impossible to obtain a random sample of the population. In such cases, it will be important to consider how representative the resulting sample will be.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;paired-samples&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Paired samples&lt;/h1&gt;
&lt;p&gt;Last but not least, paired samples are samples in which groups (often pairs) of experimental units are linked together by the same experimental conditions. For example, one may measure the hours of sleep for 20 patients before taking a sleeping pill (forming sample A), and then repeat the measurements on the same individuals after they have taken a sleeping pill (forming sample B). Another example is the grades of 25 students at their statistics and economics exam. Among each student, grades for these two exams are undoubtedly associated (to some extent) to each other.&lt;/p&gt;
&lt;p&gt;Paired samples are usually formed when a variable of interest is measured &lt;strong&gt;at different times on the same experimental unit&lt;/strong&gt;. But, paired samples can also occur even when measurements are made at one specific point in time. For example, if we measure the strength in the right and left arm of 30 athletes. Strength in the right and left arm for the same individual are linked to each other, so sample A (for the right arm) and sample B (for the left arm) are paired samples.&lt;/p&gt;
&lt;p&gt;The two measurements for each individual (hours of sleep before and after the sleeping pill, grades at two different exams, or the strength in the right and left arm) and the two samples are of course related. Statistical tools accounting for a relation between the samples exist and should be preferred in that case.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;To summarize, the sample is the group of individuals who participated in the study and the population is the broader group to whom the results will apply. Measurements on the entire population is often too complex or impossible, so representative samples are used to draw conclusions about the population. Samples based on a random selection are often the most representative samples.&lt;/p&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope the article helped you to understand the difference between population and sample. For the interested reader, see the most common &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics&lt;/a&gt; that can be made on a sample or a population.&lt;/p&gt;
&lt;p&gt;As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&#34;footnotes footnotes-end-of-document&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn1&#34;&gt;&lt;p&gt;There can be, however, many different samples from the same population. This is beyond the scope of this article, and at the moment we assume there is only one sample from a specified population.&lt;a href=&#34;#fnref1&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id=&#34;fn2&#34;&gt;&lt;p&gt;The tools used to describe a population are called parameters, whereas the tools used to describe a sample are referred as statistics. See the most common &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;descriptive statistics&lt;/a&gt; for a sample and a population.&lt;a href=&#34;#fnref2&#34; class=&#34;footnote-back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>A guide on how to read statistical tables</title>
      <link>https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/</link>
      <pubDate>Mon, 06 Jan 2020 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/a-guide-on-how-to-read-statistical-tables/</guid>
      <description>


&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/a-guide-on-how-to-read-statistics-table_files/Probability-distributions-statsandr.com.png&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Below a Shiny app to help you read the main statistical tables:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-101/&#34; target=&#34;_blank&#34;&gt;Statistics-101&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This Shiny app helps you to compute probabilities for the main probability distributions.&lt;/p&gt;
&lt;div id=&#34;how-to-use-this-app&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How to use this app?&lt;/h1&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Open the app via this &lt;a href=&#34;https://antoinesoetewey.shinyapps.io/statistics-101/&#34; target=&#34;_blank&#34;&gt;link&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Choose the distribution&lt;/li&gt;
&lt;li&gt;Set the parameter(s) of the distribution (the parameters depend of course on the chosen distribution)&lt;/li&gt;
&lt;li&gt;Select whether you want to find the lower tail, upper tail or an interval&lt;/li&gt;
&lt;li&gt;Choose the value of x&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;On the right panel (or below depending on the size of your screen) you will see:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a recap of the data you just entered&lt;/li&gt;
&lt;li&gt;the numerical solution (i.e., the probability)&lt;/li&gt;
&lt;li&gt;a visualization of the solution&lt;/li&gt;
&lt;li&gt;the probability density function together with the mean, the standard deviation and the variance&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;example&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Example&lt;/h1&gt;
&lt;p&gt;Here is an example with the most common distribution: the &lt;strong&gt;&lt;a href=&#34;https://statsandr.com/blog/do-my-data-follow-a-normal-distribution-a-note-on-the-most-widely-used-distribution-and-how-to-test-for-normality-in-r/&#34;&gt;normal distribution&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Suppose the following problem: The cost of weekly maintenance and repair of a business has been observed over a long period of time and turns out to be distributed according to a normal distribution with an average of 402€ and a standard deviation of 22€. Having set a budget of 439€ for next week, what is the probability that the cost exceeds this budget?&lt;/p&gt;
&lt;p&gt;To solve this problem, follow these steps in the app:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Choose the normal distribution, as it is said that the costs follow a normal distribution&lt;/li&gt;
&lt;li&gt;Set the mean &lt;span class=&#34;math inline&#34;&gt;\(\mu\)&lt;/span&gt; equal to 402, as it is said that the average cost is 402€&lt;/li&gt;
&lt;li&gt;In the statement, the standard deviation is given (and not the variance) so select “Standard deviation &lt;span class=&#34;math inline&#34;&gt;\(\sigma\)&lt;/span&gt;” and set it equal to 22&lt;/li&gt;
&lt;li&gt;We are asked what is the probability the the cost &lt;strong&gt;exceeds&lt;/strong&gt; the budget. Therefore, we look for the probability &lt;strong&gt;above&lt;/strong&gt; a certain x, so select upper tail &lt;span class=&#34;math inline&#34;&gt;\(P(X &amp;gt; x)\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;We are now asked to find the probability that the cost exceeds 439€, so set x equal to 439&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The solution panel gives a recap of the data:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[X ∼ \mathcal{N}(\mu = 402, \sigma^2 = 484)\]&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(484 = 22^2\)&lt;/span&gt;, and the solution: &lt;span class=&#34;math display&#34;&gt;\[P(X &amp;gt; 439) = P(Z &amp;gt; 1.68) = 0.0463\]&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(Z = \frac{X - \mu}{\sigma} = \frac{439 - 402}{22} = 1.68\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(Z ∼ \mathcal{N}(\mu = 0, \sigma^2 = 1)\)&lt;/span&gt; (known as the standard normal distribution). Thus, the probability that the cost next week exceeds the budget of 439€ is 0.0463, or 4.63%.&lt;/p&gt;
&lt;p&gt;It also shows the normal distribution (with &lt;span class=&#34;math inline&#34;&gt;\(\mu = 402\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(\sigma^2 = 484\)&lt;/span&gt;) with the shaded area corresponding to the probability we are looking for. It then gives some details about the density function, the mean, the standard deviation and the variance.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;code&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Code&lt;/h1&gt;
&lt;p&gt;See the last version on &lt;a href=&#34;https://github.com/AntoineSoetewey/statistics-101&#34; target=&#34;_blank&#34;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note that the link may not work if the app has hit the monthly usage limit. Try again later if that is the case.&lt;/em&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope you will find this app useful to compute probabilities for the main distributions.&lt;/p&gt;
&lt;p&gt;As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Data types in R</title>
      <link>https://statsandr.com/blog/data-types-in-r/</link>
      <pubDate>Mon, 30 Dec 2019 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/data-types-in-r/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#what-data-types-exist-in-r&#34; id=&#34;toc-what-data-types-exist-in-r&#34;&gt;What data types exist in R?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#numeric&#34; id=&#34;toc-numeric&#34;&gt;Numeric&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#integer&#34; id=&#34;toc-integer&#34;&gt;Integer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#character&#34; id=&#34;toc-character&#34;&gt;Character&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#factor&#34; id=&#34;toc-factor&#34;&gt;Factor&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#logical&#34; id=&#34;toc-logical&#34;&gt;Logical&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/data-types-in-r_files/0_Lck0ET_fVy_P3VNK.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;This article presents the different data types in R. To learn about the different variable types from a statistical point of view, read “&lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/&#34;&gt;Variable types and examples&lt;/a&gt;”.&lt;/p&gt;
&lt;div id=&#34;what-data-types-exist-in-r&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;What data types exist in R?&lt;/h1&gt;
&lt;p&gt;There are the 6 most common data types in R:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Numeric&lt;/li&gt;
&lt;li&gt;Integer&lt;/li&gt;
&lt;li&gt;Complex&lt;/li&gt;
&lt;li&gt;Character&lt;/li&gt;
&lt;li&gt;Factor&lt;/li&gt;
&lt;li&gt;Logical&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Datasets in R are often a combination of these 6 different data types. Below we explore in more detail each data types one by one, except the data type “complex” as we focus on the main ones and this data type is rarely used in practice.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;numeric&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Numeric&lt;/h1&gt;
&lt;p&gt;The most common data type in R is numeric. A variable or a series will be stored as numeric data if the values are numbers or if the values contains decimals. For example, the following two series are stored as numeric by default:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# numeric series without decimals
num_data &amp;lt;- c(3, 7, 2)
num_data&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 3 7 2&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;class(num_data)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;numeric&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# numeric series with decimals
num_data_dec &amp;lt;- c(3.4, 7.1, 2.9)
num_data_dec&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 3.4 7.1 2.9&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;class(num_data_dec)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;numeric&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# also possible to check the class thanks to str()
str(num_data_dec)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  num [1:3] 3.4 7.1 2.9&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In other words, if you assign one or several numbers to an object in R, it will be stored as numeric by default (numbers with decimals), unless specified otherwise.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;integer&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Integer&lt;/h1&gt;
&lt;p&gt;Integer data type is actually a special case of numeric data. Integers are numeric data without decimals. It can be used if you are sure that the numbers you store will never contains decimals. For example, let’s say you are interested in the number of children in a sample of 10 families. This variable is a discrete variable (see a reminder on the &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/&#34;&gt;variable types&lt;/a&gt; if you do not remember what is a discrete variable) and will never have decimals. Therefore, it can be stored as integer data thanks to the &lt;code&gt;as.integer()&lt;/code&gt; command:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;children&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1] 1 3 2 2 4 4 1 1 1 4&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;children &amp;lt;- as.integer(children)
class(children)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;integer&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that if your variable does not have decimals, R will automatically set the type as integers instead of numeric.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;character&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Character&lt;/h1&gt;
&lt;p&gt;The data type character is used when storing text, known as strings in R. The simplest ways to store data under the character format is by using &lt;code&gt;&#34;&#34;&lt;/code&gt; around the piece of text:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;char &amp;lt;- &amp;quot;some text&amp;quot;
char&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;some text&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;class(char)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;character&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you want to force any kind of data to be stored as character, you can do it by using the command &lt;code&gt;as.character()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;char2 &amp;lt;- as.character(children)
char2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1] &amp;quot;1&amp;quot; &amp;quot;3&amp;quot; &amp;quot;2&amp;quot; &amp;quot;2&amp;quot; &amp;quot;4&amp;quot; &amp;quot;4&amp;quot; &amp;quot;1&amp;quot; &amp;quot;1&amp;quot; &amp;quot;1&amp;quot; &amp;quot;4&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;class(char2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;character&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that everything inside &lt;code&gt;&#34;&#34;&lt;/code&gt; will be considered as character, no matter if it looks like character or not. For example:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;chars &amp;lt;- c(&amp;quot;7.42&amp;quot;)
chars&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;7.42&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;class(chars)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;character&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Furthermore, as soon as there is at least one character value inside a variable or vector, the whole variable or vector will be considered as character:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;char_num &amp;lt;- c(&amp;quot;text&amp;quot;, 1, 3.72, 4)
char_num&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;text&amp;quot; &amp;quot;1&amp;quot;    &amp;quot;3.72&amp;quot; &amp;quot;4&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;class(char_num)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;character&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Last but not least, although space does not matter in numeric data, it does matter for character data:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;num_space &amp;lt;- c(1)
num_nospace &amp;lt;- c(1)
# is num_space equal to num_nospace?
num_space == num_nospace&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;char_space &amp;lt;- &amp;quot;text &amp;quot;
char_nospace &amp;lt;- &amp;quot;text&amp;quot;
# is char_space equal to char_nospace?
char_space == char_nospace&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] FALSE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see from the results above, a space within character data (i.e., within &lt;code&gt;&#34;&#34;&lt;/code&gt;) makes it a different string in R!&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;factor&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Factor&lt;/h1&gt;
&lt;p&gt;Factor variables are a special case of character variables in the sense that it also contains text. However, factor variables are used when there are a limited number of unique character strings. It often represents a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/&#34;&gt;categorical variable&lt;/a&gt;. For instance, the gender will usually take on only two values, “female” or “male” (and will be considered as a factor variable) whereas the name will generally have lots of possibilities (and thus will be considered as a character variable). To create a factor variable use the &lt;code&gt;factor()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;gender &amp;lt;- factor(c(&amp;quot;female&amp;quot;, &amp;quot;female&amp;quot;, &amp;quot;male&amp;quot;, &amp;quot;female&amp;quot;, &amp;quot;male&amp;quot;))
gender&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] female female male   female male  
## Levels: female male&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To know the different levels of a factor variable, use &lt;code&gt;levels()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;levels(gender)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;female&amp;quot; &amp;quot;male&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By default, the levels are sorted alphabetically. You can reorder the levels with the argument &lt;code&gt;levels&lt;/code&gt; in the &lt;code&gt;factor()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;gender &amp;lt;- factor(gender, levels = c(&amp;quot;male&amp;quot;, &amp;quot;female&amp;quot;))
levels(gender)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;male&amp;quot;   &amp;quot;female&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Character strings can be converted to factors with &lt;code&gt;as.factor()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;text &amp;lt;- c(&amp;quot;test1&amp;quot;, &amp;quot;test2&amp;quot;, &amp;quot;test1&amp;quot;, &amp;quot;test1&amp;quot;) # create a character vector
class(text) # to know the class&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;character&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;text_factor &amp;lt;- as.factor(text) # transform to factor
class(text_factor) # recheck the class&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;factor&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The character strings have been transformed to factors, as shown by its class of the type &lt;code&gt;factor&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;logical&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Logical&lt;/h1&gt;
&lt;p&gt;A logical variable is a variable with only two values; &lt;code&gt;TRUE&lt;/code&gt; or &lt;code&gt;FALSE&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;value1 &amp;lt;- 7
value2 &amp;lt;- 9

# is value1 greater than value2?
greater &amp;lt;- value1 &amp;gt; value2
greater&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] FALSE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;class(greater)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;logical&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# is value1 less than or equal to value2?
less &amp;lt;- value1 &amp;lt;= value2
less&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;class(less)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;logical&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is also possible to transform logical data into numeric data. After the transformation from logical to numeric with the &lt;code&gt;as.numeric()&lt;/code&gt; command, &lt;code&gt;FALSE&lt;/code&gt; values equal to 0 and &lt;code&gt;TRUE&lt;/code&gt; values equal to 1:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;greater_num &amp;lt;- as.numeric(greater)
sum(greater)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;less_num &amp;lt;- as.numeric(less)
sum(less)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Conversely, numeric data can be converted to logical data, with &lt;code&gt;FALSE&lt;/code&gt; for all values equal to 0 and &lt;code&gt;TRUE&lt;/code&gt; for all other values.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x &amp;lt;- 0
as.logical(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] FALSE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;y &amp;lt;- 5
as.logical(y)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&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 basic data types in R and their particularities. If you would like to learn more about the different variable types from a statistical point of view, read the article “&lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/&#34;&gt;Variable types and examples&lt;/a&gt;”.&lt;/p&gt;
&lt;p&gt;As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Variable types and examples</title>
      <link>https://statsandr.com/blog/variable-types-and-examples/</link>
      <pubDate>Mon, 30 Dec 2019 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/variable-types-and-examples/</guid>
      <description>
&lt;link href=&#34;https://statsandr.com/rmarkdown-libs/htmltools-fill/fill.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/rmarkdown-libs/htmlwidgets/htmlwidgets.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;https://statsandr.com/rmarkdown-libs/viz/viz.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;https://statsandr.com/rmarkdown-libs/DiagrammeR-styles/styles.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://statsandr.com/rmarkdown-libs/grViz-binding/grViz.js&#34;&gt;&lt;/script&gt;

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#introduction&#34; id=&#34;toc-introduction&#34;&gt;Introduction&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#different-types-of-variables-for-different-types-of-statistical-analysis&#34; id=&#34;toc-different-types-of-variables-for-different-types-of-statistical-analysis&#34;&gt;Different types of variables for different types of statistical analysis&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#big-picture&#34; id=&#34;toc-big-picture&#34;&gt;Big picture&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#quantitative&#34; id=&#34;toc-quantitative&#34;&gt;Quantitative&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#discrete&#34; id=&#34;toc-discrete&#34;&gt;Discrete&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#continuous&#34; id=&#34;toc-continuous&#34;&gt;Continuous&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#qualitative&#34; id=&#34;toc-qualitative&#34;&gt;Qualitative&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#nominal&#34; id=&#34;toc-nominal&#34;&gt;Nominal&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#ordinal&#34; id=&#34;toc-ordinal&#34;&gt;Ordinal&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#variable-transformations&#34; id=&#34;toc-variable-transformations&#34;&gt;Variable transformations&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#from-continuous-to-discrete&#34; id=&#34;toc-from-continuous-to-discrete&#34;&gt;From continuous to discrete&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#from-quantitative-to-qualitative&#34; id=&#34;toc-from-quantitative-to-qualitative&#34;&gt;From quantitative to qualitative&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#additional-notes&#34; id=&#34;toc-additional-notes&#34;&gt;Additional notes&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#misleading-data-encoding&#34; id=&#34;toc-misleading-data-encoding&#34;&gt;Misleading data encoding&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;div id=&#34;introduction&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Introduction&lt;/h1&gt;
&lt;p&gt;If you happen to work with datasets frequently, you probably know that each row of your dataset represents a different experimental unit (also called &lt;strong&gt;observation&lt;/strong&gt;) and each column represents a different characteristic (called &lt;strong&gt;variable&lt;/strong&gt;):&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio_files/structure-of-dataset.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Structure of a dataset. Source: R for Data Science by Hadley Wickham &amp;amp; Garrett Grolemund&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Structure of a dataset. Source: R for Data Science by Hadley Wickham &amp;amp; Garrett Grolemund&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;If you do some research on the weight and height of 100 students of your university, for example, you will most likely have a dataset containing 100 rows and 3 columns:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;one for the student’s ID (could be anonymized or not),&lt;/li&gt;
&lt;li&gt;one for the weight,&lt;/li&gt;
&lt;li&gt;and one for the height.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;These three columns represent three characteristics of the 100 students. They are called &lt;strong&gt;variables&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In this article, we are going to focus on variables, and in particular on the different types of variable that exist in statistics. (To learn about the different data types in R, read “&lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/&#34;&gt;Data types in R&lt;/a&gt;”.)&lt;/p&gt;
&lt;div id=&#34;different-types-of-variables-for-different-types-of-statistical-analysis&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Different types of variables for different types of statistical analysis&lt;/h2&gt;
&lt;p&gt;First, one may wonder why we are interested in defining the types of our variables of interest.&lt;/p&gt;
&lt;p&gt;The reason why we often class variables into different types is because not all statistical analyses can be performed on all variable types. For instance, it is impossible to compute the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#mean&#34;&gt;mean&lt;/a&gt; of the variable “hair color” as you cannot sum brown and blond hair.&lt;/p&gt;
&lt;p&gt;On the other hand, finding the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#mode&#34;&gt;mode&lt;/a&gt; of a continuous variable does not really make any sense because most of the time there will not be two exact same values, so there will be no mode. And even in the case there is a mode, there will be very few observations with this value. As an example, try finding the mode of the height of the students in your class. If you are lucky, a couple of students will have the same size. However, most of the time, every student will have a different size (especially if heights have been measured in millimeters) and thus there will be no mode. To see what kind of analysis is possible on each type of variable, see more details in the articles “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-by-hand/&#34;&gt;Descriptive statistics by hand&lt;/a&gt;” and “&lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;Descriptive statistics in R&lt;/a&gt;”.&lt;/p&gt;
&lt;p&gt;Similarly, some &lt;a href=&#34;https://statsandr.com/blog/what-statistical-test-should-i-do/&#34;&gt;statistical tests&lt;/a&gt; can only be performed on certain type of variables. For example, the Pearson &lt;a href=&#34;https://statsandr.com/blog/correlation-coefficient-and-correlation-test-in-r/&#34;&gt;correlation&lt;/a&gt; is usually computed on two quantitative variables, while a &lt;a href=&#34;https://statsandr.com/blog/chi-square-test-of-independence-in-r/&#34;&gt;Chi-square test of independence&lt;/a&gt; is done with two qualitative variables, and a &lt;a href=&#34;https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/&#34;&gt;Student t-test&lt;/a&gt; or &lt;a href=&#34;https://statsandr.com/blog/anova-in-r/&#34;&gt;ANOVA&lt;/a&gt; requires a mix of one quantitative and one qualitative variable.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;big-picture&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Big picture&lt;/h1&gt;
&lt;p&gt;In statistics, variables are classified into 4 different types:&lt;/p&gt;
&lt;div class=&#34;grViz html-widget html-fill-item&#34; id=&#34;htmlwidget-1&#34; style=&#34;width:100%;height:480px;&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-1&#34;&gt;{&#34;x&#34;:{&#34;diagram&#34;:&#34;digraph {\n\n\n\n\n  \&#34;1\&#34; [label = \&#34;Variable\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fillcolor = \&#34;LightGray\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Variable\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;2\&#34; [label = \&#34;Qualitative\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fillcolor = \&#34;LightGray\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Qualitative\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;3\&#34; [label = \&#34;Nominal\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fillcolor = \&#34;LightGray\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Nominal\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;4\&#34; [label = \&#34;Ordinal\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fillcolor = \&#34;LightGray\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Ordinal\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;5\&#34; [label = \&#34;Quantitative\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fillcolor = \&#34;LightGray\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Quantitative\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;6\&#34; [label = \&#34;Discrete\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fillcolor = \&#34;LightGray\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Discrete\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;7\&#34; [label = \&#34;Continuous\&#34;, style = \&#34;filled,rounded\&#34;, shape = \&#34;box\&#34;, fillcolor = \&#34;LightGray\&#34;, fontname = \&#34;helvetica\&#34;, tooltip = \&#34;- name: Continuous\&#34;, fontcolor = \&#34;#000000\&#34;] \n  \&#34;1\&#34;-&gt;\&#34;2\&#34; \n  \&#34;1\&#34;-&gt;\&#34;5\&#34; \n  \&#34;2\&#34;-&gt;\&#34;3\&#34; \n  \&#34;2\&#34;-&gt;\&#34;4\&#34; \n  \&#34;5\&#34;-&gt;\&#34;6\&#34; \n  \&#34;5\&#34;-&gt;\&#34;7\&#34; \n}&#34;,&#34;config&#34;:{&#34;engine&#34;:&#34;dot&#34;,&#34;options&#34;:null}},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;We present each type together with examples in the following sections.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;quantitative&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Quantitative&lt;/h1&gt;
&lt;p&gt;A &lt;strong&gt;quantitative&lt;/strong&gt; variable is a variable that reflects a notion of &lt;strong&gt;magnitude&lt;/strong&gt;, that is, if the values it can take are &lt;strong&gt;numbers&lt;/strong&gt;. A quantitative variable represents thus a measure and is numerical.&lt;/p&gt;
&lt;p&gt;Quantitative variables are divided into two types: &lt;strong&gt;discrete&lt;/strong&gt; and &lt;strong&gt;continuous&lt;/strong&gt;. The difference is explained in the following two sections.&lt;/p&gt;
&lt;div id=&#34;discrete&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Discrete&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Quantitative discrete&lt;/strong&gt; variables are variables for which the values it can take are &lt;strong&gt;countable&lt;/strong&gt; and have a &lt;strong&gt;finite number of possibilities&lt;/strong&gt;. The values are often (but not always) integers. Here are some examples of discrete variables:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Number of children per family&lt;/li&gt;
&lt;li&gt;Number of students in a class&lt;/li&gt;
&lt;li&gt;Number of citizens of a country&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Even if it would take a long time to count the citizens of a large country, it is still technically doable. Moreover, for all examples, the number of possibilities is &lt;strong&gt;finite&lt;/strong&gt;. Whatever the number of children in a family, it will never be 3.58 or 7.912 so the number of possibilities is a finite number and thus countable.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;continuous&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Continuous&lt;/h2&gt;
&lt;p&gt;On the other hand, &lt;strong&gt;quantitative continuous&lt;/strong&gt; variables are variables for which the values are &lt;strong&gt;not countable&lt;/strong&gt; and have an &lt;strong&gt;infinite number of possibilities&lt;/strong&gt;. For example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Age&lt;/li&gt;
&lt;li&gt;Weight&lt;/li&gt;
&lt;li&gt;Height&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For simplicity, we usually referred to years, kilograms (or pounds) and centimeters (or feet and inches) for age, weight and height respectively. However, a 28-year-old man could actually be 28 years, 7 months, 16 days, 3 hours, 4 minutes, 5 seconds, 31 milliseconds, 9 nanoseconds old.&lt;/p&gt;
&lt;p&gt;For all measurements, we usually stop at a standard level of granularity, but nothing (except our measurement tools) prevents us from going deeper, leading to an &lt;strong&gt;infinite number of potential values&lt;/strong&gt;. The fact that the values can take an infinite number of possibilities makes it uncountable.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;qualitative&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Qualitative&lt;/h1&gt;
&lt;p&gt;In opposition to quantitative variables, &lt;strong&gt;qualitative&lt;/strong&gt; variables (also referred as categorical variables or &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#factor&#34;&gt;factors&lt;/a&gt; in R) are variables that are &lt;strong&gt;not numerical&lt;/strong&gt; and which &lt;strong&gt;values fit into categories&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In other words, a &lt;strong&gt;qualitative&lt;/strong&gt; variable is a variable which takes as its values modalities, &lt;strong&gt;categories&lt;/strong&gt; or even levels, in contrast to &lt;strong&gt;quantitative&lt;/strong&gt; variables which measure a &lt;strong&gt;quantity&lt;/strong&gt; on each individual.&lt;/p&gt;
&lt;p&gt;Qualitative variables are divided into two types: &lt;strong&gt;nominal&lt;/strong&gt; and &lt;strong&gt;ordinal&lt;/strong&gt;.&lt;/p&gt;
&lt;div id=&#34;nominal&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Nominal&lt;/h2&gt;
&lt;p&gt;A &lt;strong&gt;qualitative nominal&lt;/strong&gt; variable is a qualitative variable where &lt;strong&gt;no ordering&lt;/strong&gt; is possible or implied in the levels.&lt;/p&gt;
&lt;p&gt;For example, the variable gender is nominal because there is no order in the levels (no matter how many levels you consider for the gender—only two with female/male, or more than two with female/male/ungendered/others, levels are &lt;strong&gt;un&lt;/strong&gt;ordered). Eye color is another example of a nominal variable because there is no order among blue, brown or green eyes.&lt;/p&gt;
&lt;p&gt;A nominal variable can have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;two levels (e.g., do you smoke? Yes/No, or are you pregnant? Yes/No), or&lt;/li&gt;
&lt;li&gt;a large number of levels (what is your college major? Each major is a level in that case).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that a qualitative variable with exactly 2 levels is also referred as a &lt;strong&gt;binary&lt;/strong&gt; or &lt;strong&gt;dichotomous&lt;/strong&gt; variable.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;ordinal&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Ordinal&lt;/h2&gt;
&lt;p&gt;On the other hand, a &lt;strong&gt;qualitative ordinal&lt;/strong&gt; variable is a qualitative variable with an &lt;strong&gt;order implied in the levels&lt;/strong&gt;. For instance, if the severity of road accidents has been measured on a scale such as light, moderate and fatal accidents, this variable is a qualitative ordinal variable because there is a clear order in the levels.&lt;/p&gt;
&lt;p&gt;Another good example is health, which can take values such as poor, reasonable, good, or excellent. Again, there is a clear order in these levels so health is in this case a qualitative ordinal variable.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;variable-transformations&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Variable transformations&lt;/h1&gt;
&lt;p&gt;There are two main variable transformations:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;From a continuous to a discrete variable&lt;/li&gt;
&lt;li&gt;From a quantitative to a qualitative variable&lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&#34;from-continuous-to-discrete&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;From continuous to discrete&lt;/h2&gt;
&lt;p&gt;Let’s say we are interested in babies’ ages. The data collected is the age of the babies, so a quantitative continuous variable. However, we may work with only the number of weeks since birth and thus transforming the age into a discrete variable. The variable age remains a quantitative continuous variable but the variable we are working on (i.e., the number of weeks since birth) can be seen as a quantitative discrete variable.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;from-quantitative-to-qualitative&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;From quantitative to qualitative&lt;/h2&gt;
&lt;p&gt;Let’s say we are interested in the Body Mass Index (BMI). For this, a researcher collects data on height and weight of individuals and computes the BMI. The BMI is a quantitative continuous variable but the researcher may want to turn it into a qualitative variable by categorizing individuals below a certain threshold as underweight, above a certain threshold as overweight and the rest as normal weight. The raw BMI is a quantitative continuous variable but the categorization of the BMI makes the transformed variable a qualitative (ordinal) variable, where the levels are in this case underweight &amp;lt; normal &amp;lt; overweight.&lt;/p&gt;
&lt;p&gt;Same goes for age when age is transformed to a qualitative ordinal variable with levels such as minors, adults and seniors. It is also often the case (especially in surveys) that the variable salary (quantitative continuous) is transformed into a qualitative ordinal variable with different range of salaries (e.g., &amp;lt; 1000€, 1000 - 2000€, &amp;gt; 2000€).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;additional-notes&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Additional notes&lt;/h1&gt;
&lt;div id=&#34;misleading-data-encoding&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Misleading data encoding&lt;/h2&gt;
&lt;p&gt;Last but not least, in datasets it is very often the case that numbers are used for qualitative variables. For instance, a researcher may assign the number “1” to women and the number “2” to men (or “0” to the answer “No” and “1” to the answer “Yes”). Despite the numerical classification, the variable gender is still a qualitative variable and not a discrete variable as it may look. The numerical classification is only used to facilitate data collection and data management. It is indeed easier to write the number “1” or “2” instead of “women” or “men”, and thus less prone to encoding errors.&lt;/p&gt;
&lt;p&gt;The same goes for the identification of each observation. Suppose you collected information on 100 students. You may use their student’s ID to identify them in the dataset (so that you can trace them back). Most of the time, students’ ID (or ID in general) are encoded as numeric values. At first sight, it may thus look like a quantitative variable (because it goes from 1 to 100 for example). However, ID is clearly not a quantitative variable because it actually corresponds to an anonymized version of the student’s first and last name. If you think about it, it would make no sense to compute the mean or median on the IDs, as it does not represent a numerical measurement (but rather just an easier way to identify students than with their names).&lt;/p&gt;
&lt;p&gt;If you face this kind of setup, do not forget to &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/#categorical-variables-and-labels-management&#34;&gt;transform&lt;/a&gt; your variable into the right type before performing any statistical analyses. Usually, a basic &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive analysis&lt;/a&gt; (and knowledge about the variables which have been measured) prior to the main statistical analyses is enough to check that all variable types are correct.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;Thanks for reading.&lt;/p&gt;
&lt;p&gt;I hope this article helped you to understand the different types of variable. If you would like to learn more about the different data types in R, read the article “&lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/&#34;&gt;Data types in R&lt;/a&gt;”.&lt;/p&gt;
&lt;p&gt;As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Data manipulation in R</title>
      <link>https://statsandr.com/blog/data-manipulation-in-r/</link>
      <pubDate>Tue, 24 Dec 2019 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/data-manipulation-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;#vectors&#34; id=&#34;toc-vectors&#34;&gt;Vectors&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#concatenation&#34; id=&#34;toc-concatenation&#34;&gt;Concatenation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#seq-and-rep&#34; id=&#34;toc-seq-and-rep&#34;&gt;&lt;code&gt;seq()&lt;/code&gt; and &lt;code&gt;rep()&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#assignment&#34; id=&#34;toc-assignment&#34;&gt;Assignment&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#elements-of-a-vector&#34; id=&#34;toc-elements-of-a-vector&#34;&gt;Elements of a vector&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#type-and-length&#34; id=&#34;toc-type-and-length&#34;&gt;Type and length&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#finding-the-vector-type&#34; id=&#34;toc-finding-the-vector-type&#34;&gt;Finding the vector type&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#modifications-of-type-and-length&#34; id=&#34;toc-modifications-of-type-and-length&#34;&gt;Modifications of type and length&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#numerical-operators&#34; id=&#34;toc-numerical-operators&#34;&gt;Numerical operators&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#logical-operators&#34; id=&#34;toc-logical-operators&#34;&gt;Logical operators&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#all-and-any&#34; id=&#34;toc-all-and-any&#34;&gt;&lt;code&gt;all()&lt;/code&gt; and &lt;code&gt;any()&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#operations-on-character-strings-vector&#34; id=&#34;toc-operations-on-character-strings-vector&#34;&gt;Operations on character strings vector&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#orders-and-vectors&#34; id=&#34;toc-orders-and-vectors&#34;&gt;Orders and vectors&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#factors&#34; id=&#34;toc-factors&#34;&gt;Factors&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#creating-factors&#34; id=&#34;toc-creating-factors&#34;&gt;Creating factors&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#properties&#34; id=&#34;toc-properties&#34;&gt;Properties&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#handling&#34; id=&#34;toc-handling&#34;&gt;Handling&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#lists&#34; id=&#34;toc-lists&#34;&gt;Lists&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#creating-lists&#34; id=&#34;toc-creating-lists&#34;&gt;Creating lists&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#handling-1&#34; id=&#34;toc-handling-1&#34;&gt;Handling&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#getting-details-on-an-object&#34; id=&#34;toc-getting-details-on-an-object&#34;&gt;Getting details on an object&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#data-frames&#34; id=&#34;toc-data-frames&#34;&gt;Data frames&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#line-and-column-names&#34; id=&#34;toc-line-and-column-names&#34;&gt;Line and column names&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#subset-a-data-frame&#34; id=&#34;toc-subset-a-data-frame&#34;&gt;Subset a data frame&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#first-or-last-observations&#34; id=&#34;toc-first-or-last-observations&#34;&gt;First or last observations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#random-sample-of-observations&#34; id=&#34;toc-random-sample-of-observations&#34;&gt;Random sample of observations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#based-on-row-or-column-numbers&#34; id=&#34;toc-based-on-row-or-column-numbers&#34;&gt;Based on row or column numbers&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#based-on-variable-names&#34; id=&#34;toc-based-on-variable-names&#34;&gt;Based on variable names&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#based-on-one-or-multiple-criterion&#34; id=&#34;toc-based-on-one-or-multiple-criterion&#34;&gt;Based on one or multiple criterion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#create-a-new-variable&#34; id=&#34;toc-create-a-new-variable&#34;&gt;Create a new variable&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#transform-a-continuous-variable-into-a-categorical-variable&#34; id=&#34;toc-transform-a-continuous-variable-into-a-categorical-variable&#34;&gt;Transform a continuous variable into a categorical variable&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#sum-and-mean-in-rows&#34; id=&#34;toc-sum-and-mean-in-rows&#34;&gt;Sum and mean in rows&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#sum-and-mean-in-column&#34; id=&#34;toc-sum-and-mean-in-column&#34;&gt;Sum and mean in column&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#categorical-variables-and-labels-management&#34; id=&#34;toc-categorical-variables-and-labels-management&#34;&gt;Categorical variables and labels management&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#recode-categorical-variables&#34; id=&#34;toc-recode-categorical-variables&#34;&gt;Recode categorical variables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#change-reference-level&#34; id=&#34;toc-change-reference-level&#34;&gt;Change reference level&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#rename-variable-names&#34; id=&#34;toc-rename-variable-names&#34;&gt;Rename variable names&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#create-a-data-frame-manually&#34; id=&#34;toc-create-a-data-frame-manually&#34;&gt;Create a data frame manually&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#merging-two-data-frames&#34; id=&#34;toc-merging-two-data-frames&#34;&gt;Merging two data frames&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#add-new-observations-from-another-data-frame&#34; id=&#34;toc-add-new-observations-from-another-data-frame&#34;&gt;Add new observations from another data frame&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#add-new-variables-from-another-data-frame&#34; id=&#34;toc-add-new-variables-from-another-data-frame&#34;&gt;Add new variables from another data frame&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#missing-values&#34; id=&#34;toc-missing-values&#34;&gt;Missing values&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#remove-nas&#34; id=&#34;toc-remove-nas&#34;&gt;Remove NAs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#impute-nas&#34; id=&#34;toc-impute-nas&#34;&gt;Impute NAs&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#scale&#34; id=&#34;toc-scale&#34;&gt;Scale&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#dates-and-times&#34; id=&#34;toc-dates-and-times&#34;&gt;Dates and times&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#dates&#34; id=&#34;toc-dates&#34;&gt;Dates&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#times&#34; id=&#34;toc-times&#34;&gt;Times&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#extraction-from-dates&#34; id=&#34;toc-extraction-from-dates&#34;&gt;Extraction from dates&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#exporting-and-saving&#34; id=&#34;toc-exporting-and-saving&#34;&gt;Exporting and saving&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#looking-for-help&#34; id=&#34;toc-looking-for-help&#34;&gt;Looking for help&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/data-manipulation-in-rstudio_files/0_voEJp2o-Z2k4-uUd.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 a workshop entitled “Introduction to data analysis with R”, given by UCLouvain’s Statistical Methodology and Computing Service. See all their workshops on their &lt;a href=&#34;https://sites.uclouvain.be/training/smcs/index.php?l=en&#34; target=&#34;_blank&#34;&gt;website&lt;/a&gt;.&lt;/em&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;Not all data frames are as clean and tidy as you would expect. Therefore, after &lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/&#34;&gt;importing your data frame into RStudio&lt;/a&gt;, most of the time you will need to prepare it before performing any statistical analyses. Data manipulation can even sometimes take longer than the actual analyses when the quality of the data is poor.&lt;/p&gt;
&lt;p&gt;Data manipulation include a broad range of tools and techniques. We present here in details the manipulations that you will most likely need for your projects in R. Do not hesitate to let me know (as a comment at the end of this article for example) if you find other data manipulations essential so that I can add them.&lt;/p&gt;
&lt;p&gt;In this article we show the main functions to manipulate data in R. We first illustrate these functions on vectors, &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#factor&#34;&gt;factors&lt;/a&gt; and lists. We then illustrate the main functions to manipulate data frames and dates/times in R.&lt;/p&gt;
&lt;p&gt;For those who are interested in going further, see also an introduction to &lt;a href=&#34;https://statsandr.com/blog/introduction-to-data-manipulation-in-r-with-dplyr/&#34;&gt;data manipulation in R with the &lt;code&gt;{dplyr}&lt;/code&gt; package&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;vectors&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Vectors&lt;/h1&gt;
&lt;div id=&#34;concatenation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Concatenation&lt;/h2&gt;
&lt;p&gt;We can concatenate (i.e., combine) numbers or strings with &lt;code&gt;c()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;c(2, 4, -1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  2  4 -1&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;c(1, 5 / 6, 2^3, -0.05)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  1.0000000  0.8333333  8.0000000 -0.0500000&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that by default R displays 7 decimals. You can modify it with &lt;code&gt;options(digits = 2)&lt;/code&gt; (two decimals).&lt;/p&gt;
&lt;p&gt;It is also possible to create a sequence of consecutive &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#integer&#34;&gt;integers&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;1:10&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1]  1  2  3  4  5  6  7  8  9 10&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# is the same than
c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1]  1  2  3  4  5  6  7  8  9 10&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# or
c(1:10)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1]  1  2  3  4  5  6  7  8  9 10&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;seq-and-rep&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;&lt;code&gt;seq()&lt;/code&gt; and &lt;code&gt;rep()&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;seq()&lt;/code&gt; allows to make a vector defined by a sequence. You can either choose the increment:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;seq(from = 2, to = 5, by = 0.5)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 2.0 2.5 3.0 3.5 4.0 4.5 5.0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or its length:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;seq(from = 2, to = 5, length.out = 7)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 2.0 2.5 3.0 3.5 4.0 4.5 5.0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;On the other hand, &lt;code&gt;rep()&lt;/code&gt; creates a vector which is the repetition of numbers or strings:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rep(1, times = 3)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1 1 1&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rep(c(&amp;quot;A&amp;quot;, &amp;quot;B&amp;quot;, &amp;quot;C&amp;quot;), times = c(3, 1, 2))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;A&amp;quot; &amp;quot;A&amp;quot; &amp;quot;A&amp;quot; &amp;quot;B&amp;quot; &amp;quot;C&amp;quot; &amp;quot;C&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can also create a vector which is the repetition of numbers and strings:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rep(c(&amp;quot;A&amp;quot;, 2, &amp;quot;C&amp;quot;), times = c(3, 1, 2))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;A&amp;quot; &amp;quot;A&amp;quot; &amp;quot;A&amp;quot; &amp;quot;2&amp;quot; &amp;quot;C&amp;quot; &amp;quot;C&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;but in that case, the number 2 will be considered as a string too (and not as a &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#numeric&#34;&gt;numeric&lt;/a&gt;) since there is at least one string in the vector.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;assignment&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Assignment&lt;/h2&gt;
&lt;p&gt;There are three ways to assign an object in R:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;code&gt;&amp;lt;-&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;=&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;assign()&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# 1st method
x &amp;lt;- c(2.1, 5, -4, 1, 5)
x&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  2.1  5.0 -4.0  1.0  5.0&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# 2nd method
x2 = c(2.1, 5, -4, 1, 5)
x2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  2.1  5.0 -4.0  1.0  5.0&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# 3rd method (much less common)
assign(&amp;quot;x3&amp;quot;, c(2.1, 5, -4, 1, 5))
x3&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  2.1  5.0 -4.0  1.0  5.0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can also assign a vector to another vector, for example:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;y &amp;lt;- c(x, 10, 1 / 4)
y&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  2.10  5.00 -4.00  1.00  5.00 10.00  0.25&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;elements-of-a-vector&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Elements of a vector&lt;/h2&gt;
&lt;p&gt;We can select one or several elements of a vector by specifying its position between square brackets:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# select one element
x[3]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] -4&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# select more than one element with c()
x[c(1, 3, 4)]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  2.1 -4.0  1.0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that in R the numbering of the indices starts at 1 (and no 0 like other programming languages) so &lt;code&gt;x[1]&lt;/code&gt; gives the first element of the vector &lt;code&gt;x&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;We can also use &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#logical&#34;&gt;booleans&lt;/a&gt; (i.e., &lt;code&gt;TRUE&lt;/code&gt; or &lt;code&gt;FALSE&lt;/code&gt;) to select some elements of a vector. This method selects only the elements corresponding to &lt;code&gt;TRUE&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x[c(TRUE, FALSE, TRUE, TRUE, FALSE)]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  2.1 -4.0  1.0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Or we can give the elements to withdraw:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x[-c(2, 4)]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  2.1 -4.0  5.0&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;type-and-length&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Type and length&lt;/h2&gt;
&lt;p&gt;The main types of a vector are &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#numeric&#34;&gt;numeric&lt;/a&gt;, &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#logical&#34;&gt;logical&lt;/a&gt; and &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#character&#34;&gt;character&lt;/a&gt;. For more details on each type, see the different &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/&#34;&gt;data types in R&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;class()&lt;/code&gt; gives the vector type:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x &amp;lt;- c(2.1, 5, -4, 1, 5, 0)
class(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;numeric&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;y &amp;lt;- c(x, &amp;quot;Hello&amp;quot;)
class(y)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;character&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see above, the class of a vector will be numeric only if all of its elements are numeric. As soon as one element is a character, the class of the vector will be a character.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;z &amp;lt;- c(TRUE, FALSE, FALSE)
class(z)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;logical&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;length()&lt;/code&gt; gives the length of a vector:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;length(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 6&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So to select the last element of a vector (in a dynamic way), we can use a combination of &lt;code&gt;length()&lt;/code&gt; and &lt;code&gt;[]&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x[length(x)]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;finding-the-vector-type&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Finding the vector type&lt;/h2&gt;
&lt;p&gt;We can find the type of a vector with the family of &lt;code&gt;is.type&lt;/code&gt; functions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;is.numeric(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;is.logical(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] FALSE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;is.character(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] FALSE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Or in a more generic way with the &lt;code&gt;is()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;is(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;numeric&amp;quot; &amp;quot;vector&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;modifications-of-type-and-length&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Modifications of type and length&lt;/h2&gt;
&lt;p&gt;We can change the type of a vector with the &lt;code&gt;as.numeric()&lt;/code&gt;, &lt;code&gt;as.logical()&lt;/code&gt; and &lt;code&gt;as.character()&lt;/code&gt; functions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x_character &amp;lt;- as.character(x)
x_character&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;2.1&amp;quot; &amp;quot;5&amp;quot;   &amp;quot;-4&amp;quot;  &amp;quot;1&amp;quot;   &amp;quot;5&amp;quot;   &amp;quot;0&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;is.character(x_character)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x_logical &amp;lt;- as.logical(x)
x_logical&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;is.logical(x_logical)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is also possible to change its length:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;length(x) &amp;lt;- 4
x&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  2.1  5.0 -4.0  1.0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, the first elements of the vector are conserved while all others are removed. In this case, the first 4 since we specified a length of 4.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;numerical-operators&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Numerical operators&lt;/h2&gt;
&lt;p&gt;The basic numerical operators such as &lt;code&gt;+&lt;/code&gt;, &lt;code&gt;-&lt;/code&gt;, &lt;code&gt;*&lt;/code&gt;, &lt;code&gt;/&lt;/code&gt; and &lt;code&gt;^&lt;/code&gt; can be applied to vectors:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x &amp;lt;- c(2.1, 5, -4, 1)
y &amp;lt;- c(0, -7, 1, 1 / 4)

x + y&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  2.10 -2.00 -3.00  1.25&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x * y&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]   0.00 -35.00  -4.00   0.25&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x^y&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  1.00e+00  1.28e-05 -4.00e+00  1.00e+00&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is also possible to compute the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#minimum-and-maximum&#34;&gt;minimum, maximum&lt;/a&gt;, sum, product, cumulative sum and cumulative product of a vector:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;min(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] -4&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;max(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 5&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sum(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 4.1&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;prod(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] -42&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;cumsum(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 2.1 7.1 3.1 4.1&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;cumprod(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]   2.1  10.5 -42.0 -42.0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The following mathematical operations can be applied too:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;sqrt()&lt;/code&gt; (square root)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;cos()&lt;/code&gt; (cosine)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;sin()&lt;/code&gt; (sine)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;tan()&lt;/code&gt; (tangent)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;log()&lt;/code&gt; (logarithm)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;log10()&lt;/code&gt; (base 10 logarithm)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;exp()&lt;/code&gt; (exponential)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;abs()&lt;/code&gt; (absolute value)&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;cos(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] -0.5048461  0.2836622 -0.6536436  0.5403023&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;exp(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]   8.16616991 148.41315910   0.01831564   2.71828183&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you need to round a number, you can use the &lt;code&gt;round()&lt;/code&gt;, &lt;code&gt;floor()&lt;/code&gt; and &lt;code&gt;ceiling()&lt;/code&gt; functions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;round(cos(x), digits = 3) # round to 3 decimals&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] -0.505  0.284 -0.654  0.540&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;floor(cos(x)) # largest integer not greater than x&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] -1  0 -1  0&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ceiling(cos(x)) # smallest integer not less than x&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0 1 0 1&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;logical-operators&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Logical operators&lt;/h2&gt;
&lt;p&gt;The most common logical operators in R are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Negation: &lt;code&gt;!&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Comparisons: &lt;code&gt;&amp;lt;&lt;/code&gt;, &lt;code&gt;&amp;lt;=&lt;/code&gt;, &lt;code&gt;&amp;gt;=&lt;/code&gt;, &lt;code&gt;&amp;gt;&lt;/code&gt;, &lt;code&gt;==&lt;/code&gt; (equality), &lt;code&gt;!=&lt;/code&gt; (difference)&lt;/li&gt;
&lt;li&gt;And: &lt;code&gt;&amp;amp;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Or: &lt;code&gt;|&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  2.1  5.0 -4.0  1.0&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x &amp;lt;= c(1, 6, 3, 4)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] FALSE  TRUE  TRUE  TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x &amp;lt;= 1&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] FALSE FALSE  TRUE  TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;(x == 1 | x &amp;gt; 4)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] FALSE  TRUE FALSE  TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;!(x == 1 | x &amp;gt; 4)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  TRUE FALSE  TRUE FALSE&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;all-and-any&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;&lt;code&gt;all()&lt;/code&gt; and &lt;code&gt;any()&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;As the names suggest, &lt;code&gt;all()&lt;/code&gt; return &lt;code&gt;TRUE&lt;/code&gt; if conditions are met for all elements, whereas &lt;code&gt;any()&lt;/code&gt; returns &lt;code&gt;TRUE&lt;/code&gt; if conditions are met for any of the element of a vector:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  2.1  5.0 -4.0  1.0&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x &amp;lt;= 1&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] FALSE FALSE  TRUE  TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;all(x &amp;lt;= 1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] FALSE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;any(x &amp;lt;= 1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;operations-on-character-strings-vector&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Operations on character strings vector&lt;/h2&gt;
&lt;p&gt;You can paste two vectors (or more) together:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;code &amp;lt;- paste(c(&amp;quot;BE&amp;quot;, &amp;quot;BE&amp;quot;, &amp;quot;FR&amp;quot;, &amp;quot;EN&amp;quot;, &amp;quot;BE&amp;quot;), 1:5, sep = &amp;quot;/&amp;quot;)
code&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;BE/1&amp;quot; &amp;quot;BE/2&amp;quot; &amp;quot;FR/3&amp;quot; &amp;quot;EN/4&amp;quot; &amp;quot;BE/5&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The argument &lt;code&gt;sep&lt;/code&gt; stands for &lt;code&gt;separator&lt;/code&gt; and allows to specify the character(s) or symbol(s) used to separate each character strings.&lt;/p&gt;
&lt;p&gt;If you do not want to specify a separator, you can use &lt;code&gt;sep = &#34;&#34;&lt;/code&gt; or the &lt;code&gt;paste0()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;paste(c(&amp;quot;BE&amp;quot;, &amp;quot;BE&amp;quot;, &amp;quot;FR&amp;quot;, &amp;quot;EN&amp;quot;, &amp;quot;BE&amp;quot;), 1:5, sep = &amp;quot;&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;BE1&amp;quot; &amp;quot;BE2&amp;quot; &amp;quot;FR3&amp;quot; &amp;quot;EN4&amp;quot; &amp;quot;BE5&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;paste0(c(&amp;quot;BE&amp;quot;, &amp;quot;BE&amp;quot;, &amp;quot;FR&amp;quot;, &amp;quot;EN&amp;quot;, &amp;quot;BE&amp;quot;), 1:5)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;BE1&amp;quot; &amp;quot;BE2&amp;quot; &amp;quot;FR3&amp;quot; &amp;quot;EN4&amp;quot; &amp;quot;BE5&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To find the positions of the elements containing a given string, use the &lt;code&gt;grep()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;grep(&amp;quot;BE&amp;quot;, code)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1 2 5&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To extract a character string based on the beginning and the end positions, we can use the &lt;code&gt;substr()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# extract characters 1 to 3
substr(code,
  start = 1,
  stop = 3
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;BE/&amp;quot; &amp;quot;BE/&amp;quot; &amp;quot;FR/&amp;quot; &amp;quot;EN/&amp;quot; &amp;quot;BE/&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Replace a character string by another one if it exists in the vector by using the &lt;code&gt;sub()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sub(
  pattern = &amp;quot;BE&amp;quot;, # find BE
  replacement = &amp;quot;BEL&amp;quot;, # replace it with BEL
  code
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;BEL/1&amp;quot; &amp;quot;BEL/2&amp;quot; &amp;quot;FR/3&amp;quot;  &amp;quot;EN/4&amp;quot;  &amp;quot;BEL/5&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Split a character string based on a specific symbol with the &lt;code&gt;strsplit()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;strsplit(c(&amp;quot;Rafael Nadal&amp;quot;, &amp;quot;Roger Federer&amp;quot;, &amp;quot;Novak Djokovic&amp;quot;),
  split = &amp;quot; &amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [[1]]
## [1] &amp;quot;Rafael&amp;quot; &amp;quot;Nadal&amp;quot; 
## 
## [[2]]
## [1] &amp;quot;Roger&amp;quot;   &amp;quot;Federer&amp;quot;
## 
## [[3]]
## [1] &amp;quot;Novak&amp;quot;    &amp;quot;Djokovic&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;strsplit(code,
  split = &amp;quot;/&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [[1]]
## [1] &amp;quot;BE&amp;quot; &amp;quot;1&amp;quot; 
## 
## [[2]]
## [1] &amp;quot;BE&amp;quot; &amp;quot;2&amp;quot; 
## 
## [[3]]
## [1] &amp;quot;FR&amp;quot; &amp;quot;3&amp;quot; 
## 
## [[4]]
## [1] &amp;quot;EN&amp;quot; &amp;quot;4&amp;quot; 
## 
## [[5]]
## [1] &amp;quot;BE&amp;quot; &amp;quot;5&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To transform a character vector to uppercase and lowercase:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;toupper(c(&amp;quot;Rafael Nadal&amp;quot;, &amp;quot;Roger Federer&amp;quot;, &amp;quot;Novak Djokovic&amp;quot;))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;RAFAEL NADAL&amp;quot;   &amp;quot;ROGER FEDERER&amp;quot;  &amp;quot;NOVAK DJOKOVIC&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;tolower(c(&amp;quot;Rafael Nadal&amp;quot;, &amp;quot;Roger Federer&amp;quot;, &amp;quot;Novak Djokovic&amp;quot;))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;rafael nadal&amp;quot;   &amp;quot;roger federer&amp;quot;  &amp;quot;novak djokovic&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;orders-and-vectors&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Orders and vectors&lt;/h2&gt;
&lt;p&gt;We can sort the elements of a vector from smallest to largest, or from largest to smallest:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x &amp;lt;- c(2.1, 5, -4, 1, 1)
sort(x) # smallest to largest&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] -4.0  1.0  1.0  2.1  5.0&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sort(x, decreasing = TRUE) # largest to smallest&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  5.0  2.1  1.0  1.0 -4.0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;order()&lt;/code&gt; gives the permutation to apply to the vector in order to sort its elements:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;order(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 3 4 5 1 2&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, the third element of the vector is the smallest and the second element is the largest. This is indicated by the 3 at the beginning of the output, and the 2 at the end of the output.&lt;/p&gt;
&lt;p&gt;Like &lt;code&gt;sort()&lt;/code&gt; the &lt;code&gt;decreasing = TRUE&lt;/code&gt; argument can also be added:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;order(x, decreasing = TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 2 1 4 5 3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this case, the 2 in the output indicates that the second element of the vector is the largest, while the 3 indicates that the third element is the smallest.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;rank()&lt;/code&gt; gives the ranks of the elements:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rank(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 4.0 5.0 1.0 2.5 2.5&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The two last elements of the vector have a rank of 2.5 because they are equal and they come after the first but before the fourth rank.&lt;/p&gt;
&lt;p&gt;We can also reverse the elements (from the last one to the first one):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  2.1  5.0 -4.0  1.0  1.0&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rev(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  1.0  1.0 -4.0  5.0  2.1&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;factors&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Factors&lt;/h1&gt;
&lt;p&gt;&lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#factor&#34;&gt;Factors in R&lt;/a&gt; are vectors with a list of levels, also referred as categories. Factors are useful for &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;qualitative&lt;/a&gt; data such as the gender, civil status, eye color, etc.&lt;/p&gt;
&lt;div id=&#34;creating-factors&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Creating factors&lt;/h2&gt;
&lt;p&gt;We create factors with the &lt;code&gt;factor()&lt;/code&gt; function (do not forget the &lt;code&gt;c()&lt;/code&gt;):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;f1 &amp;lt;- factor(c(&amp;quot;T1&amp;quot;, &amp;quot;T3&amp;quot;, &amp;quot;T1&amp;quot;, &amp;quot;T2&amp;quot;))
f1&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] T1 T3 T1 T2
## Levels: T1 T2 T3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can of course create a factor from an existing vector:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;v &amp;lt;- c(1, 1, 0, 1, 0)
v2 &amp;lt;- factor(v,
  levels = c(0, 1),
  labels = c(&amp;quot;bad&amp;quot;, &amp;quot;good&amp;quot;)
)
v2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] good good bad  good bad 
## Levels: bad good&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can also specify that the levels are ordered by adding the &lt;code&gt;ordered = TRUE&lt;/code&gt; argument:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;v2 &amp;lt;- factor(v,
  levels = c(0, 1),
  labels = c(&amp;quot;bad&amp;quot;, &amp;quot;good&amp;quot;),
  ordered = TRUE
)
v2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] good good bad  good bad 
## Levels: bad &amp;lt; good&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the order of the levels will follow the order that is specified in the &lt;code&gt;labels&lt;/code&gt; argument.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;properties&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Properties&lt;/h2&gt;
&lt;p&gt;To know the names of the levels:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;levels(f1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;T1&amp;quot; &amp;quot;T2&amp;quot; &amp;quot;T3&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For the number of levels:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;nlevels(f1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In R, the first level is always the reference level. This reference level can be modified with &lt;code&gt;relevel()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;relevel(f1, ref = &amp;quot;T3&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] T1 T3 T1 T2
## Levels: T3 T1 T2&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You see that “T3” is now the first and thus the reference level. Changing the reference level has an impact on the order they are displayed or treated in statistical analyses. Compare, for instance, &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#boxplot&#34;&gt;boxplots&lt;/a&gt; with different reference levels.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;handling&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Handling&lt;/h2&gt;
&lt;p&gt;To know the frequencies for each level:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;table(f1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## f1
## T1 T2 T3 
##  2  1  1&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# or
summary(f1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## T1 T2 T3 
##  2  1  1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the relative frequencies (i.e., the proportions) can be found with the combination of &lt;code&gt;prop.table()&lt;/code&gt; and &lt;code&gt;table()&lt;/code&gt; or &lt;code&gt;summary()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;prop.table(table(f1))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## f1
##   T1   T2   T3 
## 0.50 0.25 0.25&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# or
prop.table(summary(f1))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   T1   T2   T3 
## 0.50 0.25 0.25&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Remember that a factor is coded in R as a numeric vector even though it looks like a character one. We can transform a factor into its numerical equivalent with the &lt;code&gt;as.numeric()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;f1&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] T1 T3 T1 T2
## Levels: T1 T2 T3&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;as.numeric(f1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1 3 1 2&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And a numeric vector can be transformed into a factor with the &lt;code&gt;as.factor()&lt;/code&gt; or &lt;code&gt;factor()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;num &amp;lt;- 1:4
fac &amp;lt;- as.factor(num)
fac&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1 2 3 4
## Levels: 1 2 3 4&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;fac2 &amp;lt;- factor(num)
fac2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1 2 3 4
## Levels: 1 2 3 4&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The advantage of &lt;code&gt;factor()&lt;/code&gt; is that it is possible to specify a name for each level:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;fac2 &amp;lt;- factor(num,
  labels = c(&amp;quot;bad&amp;quot;, &amp;quot;neutral&amp;quot;, &amp;quot;good&amp;quot;, &amp;quot;very good&amp;quot;)
)
fac2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] bad       neutral   good      very good
## Levels: bad neutral good very good&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;lists&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Lists&lt;/h1&gt;
&lt;p&gt;A list is a vector whose elements can be of different natures: a vector, a list, a factor, numeric or character, etc.&lt;/p&gt;
&lt;div id=&#34;creating-lists&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Creating lists&lt;/h2&gt;
&lt;p&gt;The function &lt;code&gt;list()&lt;/code&gt; allows to create lists:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;tahiti &amp;lt;- list(
  plane = c(&amp;quot;Airbus&amp;quot;, &amp;quot;Boeing&amp;quot;),
  departure = c(&amp;quot;Brussels&amp;quot;, &amp;quot;Milan&amp;quot;, &amp;quot;Paris&amp;quot;),
  duration = c(15, 11, 14)
)
tahiti&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $plane
## [1] &amp;quot;Airbus&amp;quot; &amp;quot;Boeing&amp;quot;
## 
## $departure
## [1] &amp;quot;Brussels&amp;quot; &amp;quot;Milan&amp;quot;    &amp;quot;Paris&amp;quot;   
## 
## $duration
## [1] 15 11 14&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;handling-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Handling&lt;/h2&gt;
&lt;p&gt;There are several methods to extract elements from a list:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;tahiti$departure&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;Brussels&amp;quot; &amp;quot;Milan&amp;quot;    &amp;quot;Paris&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# or
tahiti$de&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;Brussels&amp;quot; &amp;quot;Milan&amp;quot;    &amp;quot;Paris&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# or
tahiti[[2]]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;Brussels&amp;quot; &amp;quot;Milan&amp;quot;    &amp;quot;Paris&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# or
tahiti[[&amp;quot;departure&amp;quot;]]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;Brussels&amp;quot; &amp;quot;Milan&amp;quot;    &amp;quot;Paris&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;tahiti[[2]][c(1, 2)]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;Brussels&amp;quot; &amp;quot;Milan&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To transform a list into a vector:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;v &amp;lt;- unlist(tahiti)
v&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##     plane1     plane2 departure1 departure2 departure3  duration1  duration2 
##   &amp;quot;Airbus&amp;quot;   &amp;quot;Boeing&amp;quot; &amp;quot;Brussels&amp;quot;    &amp;quot;Milan&amp;quot;    &amp;quot;Paris&amp;quot;       &amp;quot;15&amp;quot;       &amp;quot;11&amp;quot; 
##  duration3 
##       &amp;quot;14&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;is.vector(v)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;getting-details-on-an-object&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Getting details on an object&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;attributes()&lt;/code&gt; gives the names of the elements (it can be used on every R object):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;attributes(tahiti)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $names
## [1] &amp;quot;plane&amp;quot;     &amp;quot;departure&amp;quot; &amp;quot;duration&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;str()&lt;/code&gt; gives a short description about the elements (it can also be used on every R object):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;str(tahiti)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## List of 3
##  $ plane    : chr [1:2] &amp;quot;Airbus&amp;quot; &amp;quot;Boeing&amp;quot;
##  $ departure: chr [1:3] &amp;quot;Brussels&amp;quot; &amp;quot;Milan&amp;quot; &amp;quot;Paris&amp;quot;
##  $ duration : num [1:3] 15 11 14&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;data-frames&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Data frames&lt;/h1&gt;
&lt;p&gt;Every imported file in R is a data frame (at least if you do not use a package to &lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/&#34;&gt;import your data in R&lt;/a&gt;). A data frame is a mix of a list and a matrix: it has the shape of a matrix but the columns can have different classes.&lt;/p&gt;
&lt;p&gt;Remember that the gold standard for a &lt;strong&gt;data frame&lt;/strong&gt; is that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;columns&lt;/strong&gt; represent &lt;strong&gt;variables&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;lines&lt;/strong&gt; correspond to &lt;strong&gt;observations&lt;/strong&gt; and&lt;/li&gt;
&lt;li&gt;each &lt;strong&gt;value&lt;/strong&gt; must have its own &lt;strong&gt;cell&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio_files/structure-of-dataset.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Structure of a data frame. Source: R for Data Science by Hadley Wickham &amp;amp; Garrett Grolemund&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Structure of a data frame. Source: R for Data Science by Hadley Wickham &amp;amp; Garrett Grolemund&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;In this article, we use the data frame &lt;code&gt;cars&lt;/code&gt; to illustrate the main data manipulation techniques. Note that the data frame is installed by default in RStudio (so you do not need to import it) and I use the generic name &lt;code&gt;dat&lt;/code&gt; as the name of the data frame throughout the article (see &lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/#user-friendly-way&#34;&gt;here&lt;/a&gt; why I always use a generic name instead of more specific names).&lt;/p&gt;
&lt;p&gt;Here is the whole data frame:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- cars # rename the cars data frame with a generic name
dat # display the entire data frame&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    speed dist
## 1      4    2
## 2      4   10
## 3      7    4
## 4      7   22
## 5      8   16
## 6      9   10
## 7     10   18
## 8     10   26
## 9     10   34
## 10    11   17
## 11    11   28
## 12    12   14
## 13    12   20
## 14    12   24
## 15    12   28
## 16    13   26
## 17    13   34
## 18    13   34
## 19    13   46
## 20    14   26
## 21    14   36
## 22    14   60
## 23    14   80
## 24    15   20
## 25    15   26
## 26    15   54
## 27    16   32
## 28    16   40
## 29    17   32
## 30    17   40
## 31    17   50
## 32    18   42
## 33    18   56
## 34    18   76
## 35    18   84
## 36    19   36
## 37    19   46
## 38    19   68
## 39    20   32
## 40    20   48
## 41    20   52
## 42    20   56
## 43    20   64
## 44    22   66
## 45    23   54
## 46    24   70
## 47    24   92
## 48    24   93
## 49    24  120
## 50    25   85&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This data frame has 50 observations with 2 variables (&lt;code&gt;speed&lt;/code&gt; and &lt;code&gt;distance&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;You can check the number of observations and variables with &lt;code&gt;nrow()&lt;/code&gt; and &lt;code&gt;ncol()&lt;/code&gt; respectively, or both at the same time with &lt;code&gt;dim()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;nrow(dat) # number of rows/observations&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 50&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ncol(dat) # number of columns/variables&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 2&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dim(dat) # dimension: number of rows and number of columns&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 50  2&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;line-and-column-names&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Line and column names&lt;/h2&gt;
&lt;p&gt;Before manipulating a data frame, it is interesting to know the line and column names:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dimnames(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [[1]]
##  [1] &amp;quot;1&amp;quot;  &amp;quot;2&amp;quot;  &amp;quot;3&amp;quot;  &amp;quot;4&amp;quot;  &amp;quot;5&amp;quot;  &amp;quot;6&amp;quot;  &amp;quot;7&amp;quot;  &amp;quot;8&amp;quot;  &amp;quot;9&amp;quot;  &amp;quot;10&amp;quot; &amp;quot;11&amp;quot; &amp;quot;12&amp;quot; &amp;quot;13&amp;quot; &amp;quot;14&amp;quot; &amp;quot;15&amp;quot;
## [16] &amp;quot;16&amp;quot; &amp;quot;17&amp;quot; &amp;quot;18&amp;quot; &amp;quot;19&amp;quot; &amp;quot;20&amp;quot; &amp;quot;21&amp;quot; &amp;quot;22&amp;quot; &amp;quot;23&amp;quot; &amp;quot;24&amp;quot; &amp;quot;25&amp;quot; &amp;quot;26&amp;quot; &amp;quot;27&amp;quot; &amp;quot;28&amp;quot; &amp;quot;29&amp;quot; &amp;quot;30&amp;quot;
## [31] &amp;quot;31&amp;quot; &amp;quot;32&amp;quot; &amp;quot;33&amp;quot; &amp;quot;34&amp;quot; &amp;quot;35&amp;quot; &amp;quot;36&amp;quot; &amp;quot;37&amp;quot; &amp;quot;38&amp;quot; &amp;quot;39&amp;quot; &amp;quot;40&amp;quot; &amp;quot;41&amp;quot; &amp;quot;42&amp;quot; &amp;quot;43&amp;quot; &amp;quot;44&amp;quot; &amp;quot;45&amp;quot;
## [46] &amp;quot;46&amp;quot; &amp;quot;47&amp;quot; &amp;quot;48&amp;quot; &amp;quot;49&amp;quot; &amp;quot;50&amp;quot;
## 
## [[2]]
## [1] &amp;quot;speed&amp;quot; &amp;quot;dist&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To know only the column names:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;names(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;speed&amp;quot; &amp;quot;dist&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# or
colnames(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;speed&amp;quot; &amp;quot;dist&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And to know only the row names:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rownames(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1] &amp;quot;1&amp;quot;  &amp;quot;2&amp;quot;  &amp;quot;3&amp;quot;  &amp;quot;4&amp;quot;  &amp;quot;5&amp;quot;  &amp;quot;6&amp;quot;  &amp;quot;7&amp;quot;  &amp;quot;8&amp;quot;  &amp;quot;9&amp;quot;  &amp;quot;10&amp;quot; &amp;quot;11&amp;quot; &amp;quot;12&amp;quot; &amp;quot;13&amp;quot; &amp;quot;14&amp;quot; &amp;quot;15&amp;quot;
## [16] &amp;quot;16&amp;quot; &amp;quot;17&amp;quot; &amp;quot;18&amp;quot; &amp;quot;19&amp;quot; &amp;quot;20&amp;quot; &amp;quot;21&amp;quot; &amp;quot;22&amp;quot; &amp;quot;23&amp;quot; &amp;quot;24&amp;quot; &amp;quot;25&amp;quot; &amp;quot;26&amp;quot; &amp;quot;27&amp;quot; &amp;quot;28&amp;quot; &amp;quot;29&amp;quot; &amp;quot;30&amp;quot;
## [31] &amp;quot;31&amp;quot; &amp;quot;32&amp;quot; &amp;quot;33&amp;quot; &amp;quot;34&amp;quot; &amp;quot;35&amp;quot; &amp;quot;36&amp;quot; &amp;quot;37&amp;quot; &amp;quot;38&amp;quot; &amp;quot;39&amp;quot; &amp;quot;40&amp;quot; &amp;quot;41&amp;quot; &amp;quot;42&amp;quot; &amp;quot;43&amp;quot; &amp;quot;44&amp;quot; &amp;quot;45&amp;quot;
## [46] &amp;quot;46&amp;quot; &amp;quot;47&amp;quot; &amp;quot;48&amp;quot; &amp;quot;49&amp;quot; &amp;quot;50&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;subset-a-data-frame&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Subset a data frame&lt;/h2&gt;
&lt;div id=&#34;first-or-last-observations&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;First or last observations&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;To keep only the first 10 observations:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;head(dat, n = 10)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    speed dist
## 1      4    2
## 2      4   10
## 3      7    4
## 4      7   22
## 5      8   16
## 6      9   10
## 7     10   18
## 8     10   26
## 9     10   34
## 10    11   17&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;To keep only the last 5 observations:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;tail(dat, n = 5)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    speed dist
## 46    24   70
## 47    24   92
## 48    24   93
## 49    24  120
## 50    25   85&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;random-sample-of-observations&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Random sample of observations&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;To draw a sample of 4 observations without replacement:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(dplyr)
sample_n(dat, 4, replace = FALSE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   speed dist
## 1    24  120
## 2    19   46
## 3     4    2
## 4    15   26&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;based-on-row-or-column-numbers&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Based on row or column numbers&lt;/h3&gt;
&lt;p&gt;If you know what observation(s) or column(s) you want to keep, you can use the row or column number(s) to subset your data frame. We illustrate this with several examples:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;keep all the variables for the &lt;span class=&#34;math inline&#34;&gt;\(3^{rd}\)&lt;/span&gt; observation:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat[3, ]&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;keep the &lt;span class=&#34;math inline&#34;&gt;\(2^{nd}\)&lt;/span&gt; variable for all observations:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat[, 2]&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;You can mix the two above methods to keep only the &lt;span class=&#34;math inline&#34;&gt;\(2^{nd}\)&lt;/span&gt; variable of the &lt;span class=&#34;math inline&#34;&gt;\(3^{rd}\)&lt;/span&gt; observation:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat[3, 2]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 4&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;keep several observations; for example observations &lt;span class=&#34;math inline&#34;&gt;\(1\)&lt;/span&gt; to &lt;span class=&#34;math inline&#34;&gt;\(5\)&lt;/span&gt;, the &lt;span class=&#34;math inline&#34;&gt;\(10^{th}\)&lt;/span&gt; and the &lt;span class=&#34;math inline&#34;&gt;\(15^{th}\)&lt;/span&gt; observation for all variables:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat[c(1:5, 10, 15), ] # do not forget c()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    speed dist
## 1      4    2
## 2      4   10
## 3      7    4
## 4      7   22
## 5      8   16
## 10    11   17
## 15    12   28&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;remove observations 5 to 45:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat[-c(5:45), ]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    speed dist
## 1      4    2
## 2      4   10
## 3      7    4
## 4      7   22
## 46    24   70
## 47    24   92
## 48    24   93
## 49    24  120
## 50    25   85&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;tip: to keep only the last observation, use &lt;code&gt;nrow()&lt;/code&gt; instead of the row number:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat[nrow(dat), ] # nrow() gives the number of rows&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    speed dist
## 50    25   85&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This way, no matter the number of observations, you will always select the last one. This technique of using a piece of code instead of a specific value is to avoid “hard coding”. Hard coding is generally not recommended (unless you want to specify a parameter that you are sure will never change) because if your data frame changes, you will need to manually edit your code.&lt;/p&gt;
&lt;p&gt;As you probably figured out by now, you can select observations and/or variables of a dataset by running &lt;code&gt;dataset_name[row_number, column_number]&lt;/code&gt;. When the row (column) number is left empty, the entire row (column) is selected.&lt;/p&gt;
&lt;p&gt;Note that all examples presented above also work for matrices:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mat &amp;lt;- matrix(c(-1, 2, 0, 3), ncol = 2, nrow = 2)
mat&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      [,1] [,2]
## [1,]   -1    0
## [2,]    2    3&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mat[1, 2]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;based-on-variable-names&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Based on variable names&lt;/h3&gt;
&lt;p&gt;To select one variable of the dataset based on its name rather than on its column number, use &lt;code&gt;dataset_name$variable_name&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat$speed&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1]  4  4  7  7  8  9 10 10 10 11 11 12 12 12 12 13 13 13 13 14 14 14 14 15 15
## [26] 15 16 16 17 17 17 18 18 18 18 19 19 19 20 20 20 20 20 22 23 24 24 24 24 25&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Accessing variables inside a data frame with this second method is strongly recommended compared to the first if you intend to modify the structure of your database. Indeed, if a column is added or removed in the data frame, the numbering will change. Therefore, variables are generally referred to by its name rather than by its position (column number). In addition, it is easier to understand and interpret code with the name of the variable written (another reason to call variables with a concise but clear name). There is only one reason why I would still use the column number; if the variables names are expected to change while the structure of the data frame will not change.&lt;/p&gt;
&lt;p&gt;To select variables, it is also possible to use the &lt;code&gt;select()&lt;/code&gt; command from the powerful &lt;code&gt;dplyr&lt;/code&gt; package (for compactness only the first 6 observations are displayed thanks to the &lt;code&gt;head()&lt;/code&gt; command):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;head(select(dat, speed))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   speed
## 1     4
## 2     4
## 3     7
## 4     7
## 5     8
## 6     9&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is equivalent than removing the distance variable:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;head(select(dat, -dist))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   speed
## 1     4
## 2     4
## 3     7
## 4     7
## 5     8
## 6     9&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;based-on-one-or-multiple-criterion&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Based on one or multiple criterion&lt;/h3&gt;
&lt;p&gt;Instead of subsetting a data frame based on row/column numbers or variable names, you can also subset it based on one or multiple criterion:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;keep only observations with speed larger than 20. The first argument refers to the name of the data frame, while the second argument refers to the subset criteria:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;subset(dat, dat$speed &amp;gt; 20)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    speed dist
## 44    22   66
## 45    23   54
## 46    24   70
## 47    24   92
## 48    24   93
## 49    24  120
## 50    25   85&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;keep only observations with distance smaller than or equal to 50 &lt;strong&gt;and&lt;/strong&gt; speed equal to 10. Note the &lt;code&gt;==&lt;/code&gt; (and not &lt;code&gt;=&lt;/code&gt;) for the equal criteria:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;subset(dat, dat$dist &amp;lt;= 50 &amp;amp; dat$speed == 10)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   speed dist
## 7    10   18
## 8    10   26
## 9    10   34&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;use &lt;code&gt;|&lt;/code&gt; to keep only observations with distance smaller than 20 &lt;strong&gt;or&lt;/strong&gt; speed equal to 10:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;subset(dat, dat$dist &amp;lt; 20 | dat$speed == 10)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    speed dist
## 1      4    2
## 2      4   10
## 3      7    4
## 5      8   16
## 6      9   10
## 7     10   18
## 8     10   26
## 9     10   34
## 10    11   17
## 12    12   14&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;to filter out some observations, use &lt;code&gt;!=&lt;/code&gt;. For instance, to keep observations with speed not equal to 24 and distance not equal to 120 (for compactness only the last 6 observations are displayed thanks to the &lt;code&gt;tail()&lt;/code&gt; command):&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;tail(subset(dat, dat$speed != 24 &amp;amp; dat$dist != 120))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    speed dist
## 41    20   52
## 42    20   56
## 43    20   64
## 44    22   66
## 45    23   54
## 50    25   85&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that it is also possible to subset a data frame with &lt;code&gt;split()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;split(dat, dat$factor_variable)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The above code will split your data frame into several lists, one for each level of the factor variable.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;create-a-new-variable&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Create a new variable&lt;/h2&gt;
&lt;p&gt;Often, a data frame can be enhanced by creating new variables based on other variables from the initial data frame, or simply by adding a new variable manually.&lt;/p&gt;
&lt;p&gt;In this example, we create two new variables; one being the speed times the distance (which we call &lt;code&gt;speed_dist&lt;/code&gt;) and the other being a categorization of the speed (which we call &lt;code&gt;speed_cat&lt;/code&gt;). We then display the first 6 observations of this new data frame with the 4 variables:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# create new variable speed_dist
dat$speed_dist &amp;lt;- dat$speed * dat$dist

# create new variable speed_cat
# with ifelse(): if dat$speed &amp;gt; 7, then speed_cat is &amp;quot;high speed&amp;quot;, otherwise it is &amp;quot;low_speed&amp;quot;
dat$speed_cat &amp;lt;- factor(ifelse(dat$speed &amp;gt; 7,
  &amp;quot;high speed&amp;quot;, &amp;quot;low speed&amp;quot;
))

# display first 6 observations
head(dat) # 6 is the default in head()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   speed dist speed_dist  speed_cat
## 1     4    2          8  low speed
## 2     4   10         40  low speed
## 3     7    4         28  low speed
## 4     7   22        154  low speed
## 5     8   16        128 high speed
## 6     9   10         90 high speed&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note than in programming, a character string is generally surrounded by quotes (e.g., &lt;code&gt;&#34;character string&#34;&lt;/code&gt;) and R is not an exception.&lt;/p&gt;
&lt;div id=&#34;transform-a-continuous-variable-into-a-categorical-variable&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Transform a continuous variable into a categorical variable&lt;/h3&gt;
&lt;p&gt;To transform a &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#continuous&#34;&gt;continuous variable&lt;/a&gt; into a categorical variable (also known as &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;qualitative variable&lt;/a&gt;):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat$speed_quali &amp;lt;- cut(dat$speed,
  breaks = c(0, 12, 15, 19, 26), # cut points
  right = FALSE # closed on the left, open on the right
)

dat[c(1:2, 23:24, 49:50), ] # display some observations&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    speed dist speed_dist  speed_cat speed_quali
## 1      4    2          8  low speed      [0,12)
## 2      4   10         40  low speed      [0,12)
## 23    14   80       1120 high speed     [12,15)
## 24    15   20        300 high speed     [15,19)
## 49    24  120       2880 high speed     [19,26)
## 50    25   85       2125 high speed     [19,26)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This transformation is for example often done on age, when the age (a continuous variable) is transformed into a qualitative variable representing different age groups.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;sum-and-mean-in-rows&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Sum and mean in rows&lt;/h3&gt;
&lt;p&gt;In survey with Likert scale (used in psychology, among others), it is often the case that we need to compute a score for each respondents based on multiple questions. The score is usually the &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/#mean&#34;&gt;mean&lt;/a&gt; or the sum of all the questions of interest.&lt;/p&gt;
&lt;p&gt;This can be done with &lt;code&gt;rowMeans()&lt;/code&gt; and &lt;code&gt;rowSums()&lt;/code&gt;. For instance, let’s compute the mean and the sum of the variables &lt;code&gt;speed&lt;/code&gt;, &lt;code&gt;dist&lt;/code&gt; and &lt;code&gt;speed_dist&lt;/code&gt; (variables must be numeric of course as a sum and a mean cannot be computed on qualitative variables!) for each row and store them under the variables &lt;code&gt;mean_score&lt;/code&gt; and &lt;code&gt;total_score&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat$mean_score &amp;lt;- rowMeans(dat[, 1:3]) # variables speed, dist and speed_dist correspond to variables 1 to 3
dat$total_score &amp;lt;- rowSums(dat[, 1:3])

head(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   speed dist speed_dist  speed_cat speed_quali mean_score total_score
## 1     4    2          8  low speed      [0,12)   4.666667          14
## 2     4   10         40  low speed      [0,12)  18.000000          54
## 3     7    4         28  low speed      [0,12)  13.000000          39
## 4     7   22        154  low speed      [0,12)  61.000000         183
## 5     8   16        128 high speed      [0,12)  50.666667         152
## 6     9   10         90 high speed      [0,12)  36.333333         109&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;sum-and-mean-in-column&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Sum and mean in column&lt;/h3&gt;
&lt;p&gt;It is also possible to compute the mean and sum by column with &lt;code&gt;colMeans()&lt;/code&gt; and &lt;code&gt;colSums()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;colMeans(dat[, 1:3])&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      speed       dist speed_dist 
##      15.40      42.98     769.64&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;colSums(dat[, 1:3])&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      speed       dist speed_dist 
##        770       2149      38482&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is equivalent than:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mean(dat$speed)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 15.4&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sum(dat$speed)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 770&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;but it allows to do it for several variables at a time.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;categorical-variables-and-labels-management&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Categorical variables and labels management&lt;/h2&gt;
&lt;p&gt;For categorical variables, it is a good practice to use the factor format and to name the different levels of the variables.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;for this example, let’s create another new variable called &lt;code&gt;dist_cat&lt;/code&gt; based on the distance and then change its format from numeric to factor (while also specifying the labels of the levels):&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# create new variable dist_cat
dat$dist_cat &amp;lt;- ifelse(dat$dist &amp;lt; 15,
  1, 2
)

# change from numeric to factor and specify the labels
dat$dist_cat &amp;lt;- factor(dat$dist_cat,
  levels = c(1, 2),
  labels = c(&amp;quot;small distance&amp;quot;, &amp;quot;big distance&amp;quot;) # follow the order of the levels
)

head(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   speed dist speed_dist  speed_cat speed_quali mean_score total_score
## 1     4    2          8  low speed      [0,12)   4.666667          14
## 2     4   10         40  low speed      [0,12)  18.000000          54
## 3     7    4         28  low speed      [0,12)  13.000000          39
## 4     7   22        154  low speed      [0,12)  61.000000         183
## 5     8   16        128 high speed      [0,12)  50.666667         152
## 6     9   10         90 high speed      [0,12)  36.333333         109
##         dist_cat
## 1 small distance
## 2 small distance
## 3 small distance
## 4   big distance
## 5   big distance
## 6 small distance&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;to check the format of a variable:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;class(dat$dist_cat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;factor&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# or
str(dat$dist_cat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  Factor w/ 2 levels &amp;quot;small distance&amp;quot;,..: 1 1 1 2 2 1 2 2 2 2 ...&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will be sufficient if you need to format only a limited number of variables. However, if you need to do it for a large amount of categorical variables, it quickly becomes time consuming to write the same code many times. As you can imagine, it possible to format many variables without having to write the entire code for each variable one by one by using the &lt;code&gt;within()&lt;/code&gt; command:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- within(dat, {
  speed_cat &amp;lt;- factor(speed_cat, labels = c(
    &amp;quot;high speed&amp;quot;,
    &amp;quot;low speed&amp;quot;
  ))
  dist_cat &amp;lt;- factor(dist_cat, labels = c(
    &amp;quot;small distance&amp;quot;,
    &amp;quot;big distance&amp;quot;
  ))
})

head(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   speed dist speed_dist  speed_cat speed_quali mean_score total_score
## 1     4    2          8  low speed      [0,12)   4.666667          14
## 2     4   10         40  low speed      [0,12)  18.000000          54
## 3     7    4         28  low speed      [0,12)  13.000000          39
## 4     7   22        154  low speed      [0,12)  61.000000         183
## 5     8   16        128 high speed      [0,12)  50.666667         152
## 6     9   10         90 high speed      [0,12)  36.333333         109
##         dist_cat
## 1 small distance
## 2 small distance
## 3 small distance
## 4   big distance
## 5   big distance
## 6 small distance&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;str(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## &amp;#39;data.frame&amp;#39;:	50 obs. of  8 variables:
##  $ speed      : num  4 4 7 7 8 9 10 10 10 11 ...
##  $ dist       : num  2 10 4 22 16 10 18 26 34 17 ...
##  $ speed_dist : num  8 40 28 154 128 90 180 260 340 187 ...
##  $ speed_cat  : Factor w/ 2 levels &amp;quot;high speed&amp;quot;,&amp;quot;low speed&amp;quot;: 2 2 2 2 1 1 1 1 1 1 ...
##  $ speed_quali: Factor w/ 4 levels &amp;quot;[0,12)&amp;quot;,&amp;quot;[12,15)&amp;quot;,..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ mean_score : num  4.67 18 13 61 50.67 ...
##  $ total_score: num  14 54 39 183 152 109 208 296 384 215 ...
##  $ dist_cat   : Factor w/ 2 levels &amp;quot;small distance&amp;quot;,..: 1 1 1 2 2 1 2 2 2 2 ...&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Alternatively, if you want to transform several numeric variables into categorical variables without changing the labels, it is best to use the &lt;code&gt;transform()&lt;/code&gt; function. We illustrate this function with the &lt;code&gt;mpg&lt;/code&gt; data frame from the &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; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggplot2)
mpg &amp;lt;- transform(mpg,
  cyl = factor(cyl),
  drv = factor(drv),
  fl = factor(fl),
  class = factor(class)
)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;recode-categorical-variables&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Recode categorical variables&lt;/h3&gt;
&lt;p&gt;It is possible to recode labels of a categorical variable if you are not satisfied with the current labels. In this example, we change the labels as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;“small distance” becomes “short distance”&lt;/li&gt;
&lt;li&gt;“big distance” becomes “large distance”&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat$dist_cat &amp;lt;- recode(dat$dist_cat,
  &amp;quot;small distance&amp;quot; = &amp;quot;short distance&amp;quot;,
  &amp;quot;big distance&amp;quot; = &amp;quot;large distance&amp;quot;
)

head(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   speed dist speed_dist  speed_cat speed_quali mean_score total_score
## 1     4    2          8  low speed      [0,12)   4.666667          14
## 2     4   10         40  low speed      [0,12)  18.000000          54
## 3     7    4         28  low speed      [0,12)  13.000000          39
## 4     7   22        154  low speed      [0,12)  61.000000         183
## 5     8   16        128 high speed      [0,12)  50.666667         152
## 6     9   10         90 high speed      [0,12)  36.333333         109
##         dist_cat
## 1 short distance
## 2 short distance
## 3 short distance
## 4 large distance
## 5 large distance
## 6 short distance&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;change-reference-level&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Change reference level&lt;/h3&gt;
&lt;p&gt;For some analyses, you might want to change the order of the levels. For example, if you are analyzing data about a control group and a treatment group, you may want to set the control group as the reference group. By default, levels are ordered by alphabetical order or by its numeric value if it was transformed from numeric to factor.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;to check the current order of the levels (the first level being the reference):&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;levels(dat$dist_cat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;short distance&amp;quot; &amp;quot;large distance&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this case, “short distance” being the first level it is the reference level. It is the first level because it was initially set with a value equal to 1 when creating the variable.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;to change the reference level:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat$dist_cat &amp;lt;- relevel(dat$dist_cat, ref = &amp;quot;large distance&amp;quot;)

levels(dat$dist_cat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;large distance&amp;quot; &amp;quot;short distance&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Large distance is now the first and thus the reference level.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;rename-variable-names&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Rename variable names&lt;/h2&gt;
&lt;p&gt;To rename variable names as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;dist &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow\)&lt;/span&gt; distance&lt;/li&gt;
&lt;li&gt;speed_dist &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow\)&lt;/span&gt; speed_distance&lt;/li&gt;
&lt;li&gt;dist_cat &lt;span class=&#34;math inline&#34;&gt;\(\rightarrow\)&lt;/span&gt; distance_cat&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;use the &lt;code&gt;rename()&lt;/code&gt; command from the &lt;code&gt;dplyr&lt;/code&gt; package:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- rename(dat,
  distance = dist,
  speed_distance = speed_dist,
  distance_cat = dist_cat
)

names(dat) # display variable names&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;speed&amp;quot;          &amp;quot;distance&amp;quot;       &amp;quot;speed_distance&amp;quot; &amp;quot;speed_cat&amp;quot;     
## [5] &amp;quot;speed_quali&amp;quot;    &amp;quot;mean_score&amp;quot;     &amp;quot;total_score&amp;quot;    &amp;quot;distance_cat&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;create-a-data-frame-manually&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Create a data frame manually&lt;/h2&gt;
&lt;p&gt;Although most analyses are performed on an imported data frame, it is also possible to create a data frame directly in R:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Create the data frame named dat with 2 variables
dat &amp;lt;- data.frame(
  &amp;quot;variable1&amp;quot; = c(6, 12, NA, 3), # presence of 1 missing value (NA)
  &amp;quot;variable2&amp;quot; = c(3, 7, 9, 1)
)

# Print the data frame
dat&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   variable1 variable2
## 1         6         3
## 2        12         7
## 3        NA         9
## 4         3         1&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;merging-two-data-frames&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Merging two data frames&lt;/h2&gt;
&lt;p&gt;By default, the merge is done on the common variables (variables that have the same name). However, if they do not have the same name, it is still possible to merge the two data frames by specifying their names:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat1 &amp;lt;- data.frame(
  person = c(1:4),
  treatment = c(&amp;quot;T1&amp;quot;, &amp;quot;T2&amp;quot;)
)

dat1&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   person treatment
## 1      1        T1
## 2      2        T2
## 3      3        T1
## 4      4        T2&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat2 &amp;lt;- data.frame(
  patient = c(1:4),
  age = c(56, 23, 32, 19),
  gender = c(&amp;quot;M&amp;quot;, &amp;quot;F&amp;quot;, &amp;quot;F&amp;quot;, &amp;quot;M&amp;quot;)
)

dat2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   patient age gender
## 1       1  56      M
## 2       2  23      F
## 3       3  32      F
## 4       4  19      M&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We want to merge the two data frames by the subject number, but this number is referred as &lt;code&gt;person&lt;/code&gt; in the first data frame and &lt;code&gt;patient&lt;/code&gt; in the second data frame, so we need to indicate it:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;merge(
  x = dat1, y = dat2,
  by.x = &amp;quot;person&amp;quot;, by.y = &amp;quot;patient&amp;quot;,
  all = TRUE
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   person treatment age gender
## 1      1        T1  56      M
## 2      2        T2  23      F
## 3      3        T1  32      F
## 4      4        T2  19      M&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;add-new-observations-from-another-data-frame&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Add new observations from another data frame&lt;/h2&gt;
&lt;p&gt;In order to add new observations from another data frame, the two data frames need to have the same column names (but they can be in a different order):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat1&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   person treatment
## 1      1        T1
## 2      2        T2
## 3      3        T1
## 4      4        T2&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat3 &amp;lt;- data.frame(
  person = 5:8,
  treatment = c(&amp;quot;T3&amp;quot;)
)

dat3&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   person treatment
## 1      5        T3
## 2      6        T3
## 3      7        T3
## 4      8        T3&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rbind(dat1, dat3) # r stands for row, so we bind data frames by row&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   person treatment
## 1      1        T1
## 2      2        T2
## 3      3        T1
## 4      4        T2
## 5      5        T3
## 6      6        T3
## 7      7        T3
## 8      8        T3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, data for persons 5 to 8 have been added at the end of the data frame &lt;code&gt;dat1&lt;/code&gt; (because &lt;code&gt;dat1&lt;/code&gt; comes before &lt;code&gt;dat3&lt;/code&gt; in the &lt;code&gt;rbind()&lt;/code&gt; function).&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;add-new-variables-from-another-data-frame&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Add new variables from another data frame&lt;/h2&gt;
&lt;p&gt;It is also possible to add new variables to a data frame with the &lt;code&gt;cbind()&lt;/code&gt; function. Unlike &lt;code&gt;rbind()&lt;/code&gt;, column names do not have to be the same since they are added next to each other:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   patient age gender
## 1       1  56      M
## 2       2  23      F
## 3       3  32      F
## 4       4  19      M&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat3&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   person treatment
## 1      5        T3
## 2      6        T3
## 3      7        T3
## 4      8        T3&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;cbind(dat2, dat3) # c stands for column, so we bind data frames by column&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   patient age gender person treatment
## 1       1  56      M      5        T3
## 2       2  23      F      6        T3
## 3       3  32      F      7        T3
## 4       4  19      M      8        T3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you want to add only a specific variable from another data frame:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat_cbind &amp;lt;- cbind(dat2, dat3$treatment)

dat_cbind&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   patient age gender dat3$treatment
## 1       1  56      M             T3
## 2       2  23      F             T3
## 3       3  32      F             T3
## 4       4  19      M             T3&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;names(dat_cbind)[4] &amp;lt;- &amp;quot;treatment&amp;quot;

dat_cbind&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   patient age gender treatment
## 1       1  56      M        T3
## 2       2  23      F        T3
## 3       3  32      F        T3
## 4       4  19      M        T3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or more simply with the &lt;code&gt;data.frame()&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;data.frame(dat2,
  treatment = dat3$treatment
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   patient age gender treatment
## 1       1  56      M        T3
## 2       2  23      F        T3
## 3       3  32      F        T3
## 4       4  19      M        T3&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;missing-values&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Missing values&lt;/h1&gt;
&lt;p&gt;Missing values (represented by NA in RStudio, for “Not Applicable”) are often problematic for many analyses because many computations including a missing value has a missing value for result.&lt;/p&gt;
&lt;p&gt;For instance, the mean of a series or variable with at least one NA will give a NA as a result. The data frame &lt;code&gt;dat&lt;/code&gt; created in the previous section is used for this example:&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;##   variable1 variable2
## 1         6         3
## 2        12         7
## 3        NA         9
## 4         3         1&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mean(dat$variable1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] NA&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;na.omit()&lt;/code&gt; function avoids the NA result, doing as if there was no missing value:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mean(na.omit(dat$variable1))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 7&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Moreover, most basic functions include an argument to deal with missing values:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mean(dat$variable1, na.rm = TRUE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 7&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;is.na()&lt;/code&gt; indicates if an element is a missing value or not:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;is.na(dat)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      variable1 variable2
## [1,]     FALSE     FALSE
## [2,]     FALSE     FALSE
## [3,]      TRUE     FALSE
## [4,]     FALSE     FALSE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that “NA” as a string is not considered as a missing value:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;y &amp;lt;- c(&amp;quot;NA&amp;quot;, &amp;quot;2&amp;quot;)

is.na(y)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] FALSE FALSE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To check whether there is at least one missing value in a vector or data frame:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;anyNA(dat$variable2) # check for NA in variable2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] FALSE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;anyNA(dat) # check for NA in the whole data frame&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# or
any(is.na(dat)) # check for NA in the whole data frame&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Nonetheless, data frames with NAs are still problematic for some types of analysis. Several alternatives exist to remove or impute missing values.&lt;/p&gt;
&lt;div id=&#34;remove-nas&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Remove NAs&lt;/h2&gt;
&lt;p&gt;A simple solution is to remove all observations (i.e., rows) containing at least one missing value. This is done by keeping only observations with complete cases:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat_complete &amp;lt;- dat[complete.cases(dat), ]
dat_complete&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   variable1 variable2
## 1         6         3
## 2        12         7
## 4         3         1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Be careful when removing observations with missing values, especially if missing values are not “missing at random”. It is not because it is possible (and easy) to remove them, that you should do it in all cases. This is, however, beyond the scope of the present article.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;impute-nas&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Impute NAs&lt;/h2&gt;
&lt;p&gt;Instead of removing observations with at least one NA, it is possible to impute them, that is, replace them by some values such as the median or the mode of the variable. This can be done easily with the command &lt;code&gt;impute()&lt;/code&gt; from the package &lt;code&gt;Hmisc&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(Hmisc)

# impute NA with default method (median/mode)
variable1 &amp;lt;- impute(dat$variable1)

# create data frame with imputed data
dat_imputed &amp;lt;- data.frame(variable1,
  variable2 = dat$variable2
)

dat_imputed&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   variable1 variable2
## 1         6         3
## 2        12         7
## 3         6         9
## 4         3         1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When the median/mode method is used (the default), character vectors and factors are imputed with the mode. Numeric and integer vectors are imputed with the median. Again, use imputations carefully. Other packages offer more advanced imputation techniques. However, we keep it simple and straightforward for this article as advanced imputations is beyond the scope of introductory data manipulations in R.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;scale&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Scale&lt;/h1&gt;
&lt;p&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;Scaling&lt;/a&gt; (also referred as standardizing) a variable is often used before a Principal Component Analysis (PCA)&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; when variables of a data frame have different units. Remember that scaling a variable means that it will compute the mean and the standard deviation of that variable. Then each value (so each row) of that variable is “scaled” by subtracting the mean and dividing by the standard deviation of that variable. Formally:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[z = \frac{x - \bar{x}}{s}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;where &lt;span class=&#34;math inline&#34;&gt;\(\bar{x}\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(s\)&lt;/span&gt; are the mean and the standard deviation of the variable, respectively.&lt;/p&gt;
&lt;p&gt;To scale one or more variables in R use &lt;code&gt;scale()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat_scaled &amp;lt;- scale(dat_imputed)

head(dat_scaled)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    variable1  variable2
## 1 -0.1986799 -0.5477226
## 2  1.3907590  0.5477226
## 3 -0.1986799  1.0954451
## 4 -0.9933993 -1.0954451&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;dates-and-times&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Dates and times&lt;/h1&gt;
&lt;div id=&#34;dates&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Dates&lt;/h2&gt;
&lt;p&gt;In R the default date format follows the rules of the ISO 8601 international standard which expresses a day as “2001-02-13” (yyyy-mm-dd).&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;Date can be defined by a string of characters or a number. For example, October 1st, 2016:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;as.Date(&amp;quot;01/10/16&amp;quot;, format = &amp;quot;%d/%m/%y&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;2016-10-01&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;as.Date(274, origin = &amp;quot;2016-01-01&amp;quot;) # there are 274 days between the origin and October 1st, 2016&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;2016-10-01&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;times&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Times&lt;/h2&gt;
&lt;p&gt;An example with date and time vectors:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dates &amp;lt;- c(&amp;quot;02/27/92&amp;quot;, &amp;quot;02/27/99&amp;quot;, &amp;quot;01/14/92&amp;quot;)
times &amp;lt;- c(&amp;quot;23:03:20&amp;quot;, &amp;quot;22:29:56&amp;quot;, &amp;quot;01:03:30&amp;quot;)

x &amp;lt;- paste(dates, times)
x&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;02/27/92 23:03:20&amp;quot; &amp;quot;02/27/99 22:29:56&amp;quot; &amp;quot;01/14/92 01:03:30&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;strptime(x,
  format = &amp;quot;%m/%d/%y %H:%M:%S&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;1992-02-27 23:03:20 CET&amp;quot; &amp;quot;1999-02-27 22:29:56 CET&amp;quot;
## [3] &amp;quot;1992-01-14 01:03:30 CET&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Find more information on how to express a date and time format with &lt;code&gt;help(strptime)&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;extraction-from-dates&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Extraction from dates&lt;/h2&gt;
&lt;p&gt;We can extract:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;weekdays&lt;/li&gt;
&lt;li&gt;months&lt;/li&gt;
&lt;li&gt;quarters&lt;/li&gt;
&lt;li&gt;years&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;y &amp;lt;- strptime(x,
  format = &amp;quot;%m/%d/%y %H:%M:%S&amp;quot;
)

y&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;1992-02-27 23:03:20 CET&amp;quot; &amp;quot;1999-02-27 22:29:56 CET&amp;quot;
## [3] &amp;quot;1992-01-14 01:03:30 CET&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;weekdays(y, abbreviate = FALSE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;Thursday&amp;quot; &amp;quot;Saturday&amp;quot; &amp;quot;Tuesday&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;months(y, abbreviate = FALSE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;February&amp;quot; &amp;quot;February&amp;quot; &amp;quot;January&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;quarters(y, abbreviate = FALSE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;Q1&amp;quot; &amp;quot;Q1&amp;quot; &amp;quot;Q1&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;format(y, &amp;quot;%Y&amp;quot;) # 4-digit year&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;1992&amp;quot; &amp;quot;1999&amp;quot; &amp;quot;1992&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;format(y, &amp;quot;%y&amp;quot;) # 2-digit year&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;92&amp;quot; &amp;quot;99&amp;quot; &amp;quot;92&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;exporting-and-saving&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Exporting and saving&lt;/h1&gt;
&lt;p&gt;If a copy-paste is not sufficient, you can save an object in R format with &lt;code&gt;save()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;save(dat, file = &amp;quot;dat.Rdata&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or using &lt;code&gt;write.table()&lt;/code&gt;, &lt;code&gt;write.csv()&lt;/code&gt; or &lt;code&gt;write.xlsx()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# in a text format
write.table(dat, &amp;quot;dat.txt&amp;quot;, row = FALSE, sep = &amp;quot;\t&amp;quot;, quote = FALSE)

# in csv
write.csv(dat, file = &amp;quot;dat.csv&amp;quot;, row.names = FALSE, quote = FALSE)

# in excel
# install.packages(&amp;quot;openxlsx&amp;quot;)
library(openxlsx)
write.xlsx(dat, file = &amp;quot;dat.xlsx&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you need to send every results into a file instead of the console:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sink(&amp;quot;filename&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;(Don’t forget to stop it with &lt;code&gt;sink()&lt;/code&gt;.)&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;looking-for-help&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Looking for help&lt;/h1&gt;
&lt;p&gt;You can always find some help about:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a function: &lt;code&gt;?function&lt;/code&gt; or &lt;code&gt;help(function)&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;a package: &lt;code&gt;help(package = packagename)&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;a concept: &lt;code&gt;help.search(&#34;concept&#34;)&lt;/code&gt; or &lt;code&gt;apropos(&#34;concept&#34;)&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Otherwise, Google is your best friend!&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 manipulate your data in RStudio. For those who are interested in going further, see also an introduction to &lt;a href=&#34;https://statsandr.com/blog/introduction-to-data-manipulation-in-r-with-dplyr/&#34;&gt;data manipulation in R with the &lt;code&gt;{dplyr}&lt;/code&gt; package&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Now that you know &lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/&#34;&gt;how to import a data frame into R&lt;/a&gt; and how to manipulate it, the next step would probably be to learn how to perform &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics in R&lt;/a&gt;. If you are looking for more advanced statistical analyses using R, see all &lt;a href=&#34;https://statsandr.com/tags/r/&#34;&gt;articles about 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 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;Principal Component Analysis (PCA) is a useful technique for exploratory data analysis, allowing a better visualization of the variation present in a data frame with a large number of variables. When there are many variables, the data cannot easily be illustrated in their raw format. To counter this, the PCA takes a data frame with many variables and simplifies it by transforming the original variables into a smaller number of “principal components”. The first dimension contains the most variance in the data frame and so on, and the dimensions are uncorrelated. Note that PCA is done on quantitative variables.&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 your information, note that this date format is not the same for every software! Excel, for instance, uses a different format.&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>How to import an Excel file in RStudio?</title>
      <link>https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/</link>
      <pubDate>Wed, 18 Dec 2019 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/</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;#transform-an-excel-file-to-a-csv-file&#34; id=&#34;toc-transform-an-excel-file-to-a-csv-file&#34;&gt;Transform an Excel file to a CSV file&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#r-working-directory&#34; id=&#34;toc-r-working-directory&#34;&gt;R working directory&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#get-working-directory&#34; id=&#34;toc-get-working-directory&#34;&gt;Get working directory&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#set-working-directory&#34; id=&#34;toc-set-working-directory&#34;&gt;Set working directory&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#user-friendly-method&#34; id=&#34;toc-user-friendly-method&#34;&gt;User-friendly method&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#via-the-console&#34; id=&#34;toc-via-the-console&#34;&gt;Via the console&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#via-the-text-editor&#34; id=&#34;toc-via-the-text-editor&#34;&gt;Via the text editor&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;#import-your-dataset&#34; id=&#34;toc-import-your-dataset&#34;&gt;Import your dataset&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#user-friendly-way&#34; id=&#34;toc-user-friendly-way&#34;&gt;User-friendly way&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#via-the-text-editor-1&#34; id=&#34;toc-via-the-text-editor-1&#34;&gt;Via the text editor&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#import-spss-.sav-files&#34; id=&#34;toc-import-spss-.sav-files&#34;&gt;Import SPSS (.sav) files&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio_files/how-to-import-an-excel-file-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;As we have seen in this article on &lt;a href=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio/&#34;&gt;how to install R and RStudio&lt;/a&gt;, R is useful for many kind of computational tasks and statistical analyses. However, it would not be so powerful and useful without the possibility to import datasets into R. As you will most likely use R with your own data, being able to import it into R is crucial for any user.&lt;/p&gt;
&lt;p&gt;In this article I present two different ways to import an Excel file; (i) via the text editor and (ii) in a more “user-friendly” way. I also discuss about the main advantages and disadvantages of both methods. Note that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;How to import a dataset often depends on the format of the file (Excel, CSV, text, SPSS, Stata, etc.). I focus here only on Excel files as it is the most common type of file for a dataset&lt;/li&gt;
&lt;li&gt;There are several other ways to import an Excel file (probably even some I am not aware of), but I present the two most simple yet robust ways to import such files&lt;/li&gt;
&lt;li&gt;No matter what type of file and how you import it, there is one gold standard regarding how datasets are structured: columns correspond to variables, rows correspond to observations (in the broad sense of the term) and each value must have its own cell (known as tidy format):&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio_files/structure-of-dataset.png&#34; alt=&#34;Structure of a dataset. Source: R for Data Science by Hadley Wickham &amp;amp; Garrett Grolemund&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Structure of a dataset. Source: R for Data Science by Hadley Wickham &amp;amp; Garrett Grolemund&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;transform-an-excel-file-to-a-csv-file&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Transform an Excel file to a CSV file&lt;/h1&gt;
&lt;p&gt;Before dealing with the importation, the first thing is to change the format of your Excel file to a CSV format.&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; CSV format is the standard when working with datasets and programming languages as it is a more robust format compared to Excel.&lt;/p&gt;
&lt;p&gt;If your file is already in the CSV format (with the extension .csv), you can skip this section. If the file is not in the CSV format (for example the extension is .xlsx) you can easily transform it to CSV by following these steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Open your Excel file&lt;/li&gt;
&lt;li&gt;Click on File &amp;gt; Save as&lt;/li&gt;
&lt;li&gt;Choose the format .csv&lt;/li&gt;
&lt;li&gt;Click on Save&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Check that your file finishes with the extension .csv. If that is the case, your file is now ready to be imported. But first, let me introduce an important concept when importing datasets into RStudio, the working directory.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;r-working-directory&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;R working directory&lt;/h1&gt;
&lt;p&gt;Although programming languages may be very powerful, it often needs our help and importing a dataset is not an exception. Indeed, before importing your data, you must tell RStudio where your file is located (so let RStudio know in which folder to look for your dataset). But before this, let me introduce the &lt;strong&gt;working directory&lt;/strong&gt;. The working directory is the location (in your computer) of where RStudio is currently working (in fact RStudio is not working across your entire computer; it is working inside one folder of your computer). Concerning this working directory, there are two functions that we will need:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;&lt;code&gt;getwd()&lt;/code&gt; (&lt;code&gt;wd&lt;/code&gt; stands for working directory)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;setwd()&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&#34;get-working-directory&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Get working directory&lt;/h2&gt;
&lt;p&gt;In most cases, when you open RStudio, the working directory (so where it is currently working) is different than where your dataset is located. To know what is the working directory RStudio is currently using, run &lt;code&gt;getwd()&lt;/code&gt;. On MacOS, this function will most likely render a location such as &lt;code&gt;&#34;/Users/yourname/&#34;&lt;/code&gt;, while on Windows it will most likely render &lt;code&gt;&#34;c:/Documents/&#34;&lt;/code&gt;. Do not worry if your working directory is different, the most important is to set the working directory correctly (so where your file is located) and not where it is now.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;set-working-directory&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Set working directory&lt;/h2&gt;
&lt;p&gt;As mentioned earlier, your dataset is most likely located in a different location than your working directory. Without any action from you, RStudio will never be able to import your file as it is not looking in the correct folder (you will encounter the following error in the console: cannot open file ‘data.csv’: No such file or directory). Now, in order to specify the correct location of your file (that is, to tell RStudio in which folder it should look for your dataset), you have three options:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;the user-friendly method&lt;/li&gt;
&lt;li&gt;via the console&lt;/li&gt;
&lt;li&gt;via the text editor (see below why it is my preferred option)&lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&#34;user-friendly-method&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;User-friendly method&lt;/h3&gt;
&lt;p&gt;To set the correct folder, so to set the working directory equal to the folder where your file is located, follow these steps:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;In the lower right pane of RStudio, click on the tab “Files”&lt;/li&gt;
&lt;li&gt;Click on “Home” next to the house icon&lt;/li&gt;
&lt;li&gt;Go to the folder where your dataset is located&lt;/li&gt;
&lt;li&gt;Click on “More”&lt;/li&gt;
&lt;li&gt;Click on “Set As Working Directory”&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio_files/set-working-directory-rstudio.png&#34; alt=&#34;Set working directory in RStudio (user-friendly method)&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Set working directory in RStudio (user-friendly method)&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;Alternatively, you can also set the working directory by clicking on Session &amp;gt; Set Working Directory &amp;gt; Choose Directory…&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio_files/set-working-directory2-rstudio.png&#34; alt=&#34;Set working directory in RStudio (user-friendly method)&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Set working directory in RStudio (user-friendly method)&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;As you can see in the console, any of the two methods will actually execute the code &lt;code&gt;setwd()&lt;/code&gt; with the path to the folder you specified. So by clicking on the buttons you actually asked RStudio to write a line of code for you. This method has the advantage that you do not need to remember the code and that you will not make a mistake in the name of the path to your folder. The disadvantage is that if you leave RStudio and open it again later, you will have to specify the working directory again as RStudio did not save your actions via the buttons.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;via-the-console&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Via the console&lt;/h3&gt;
&lt;p&gt;You can specify the working directory by running &lt;code&gt;setwd(path/to/folder)&lt;/code&gt; directly in the console, with &lt;code&gt;path/to/folder&lt;/code&gt; being the path to the folder containing your dataset. However, you will need to run the command again when reopening RStudio.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;via-the-text-editor&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Via the text editor&lt;/h3&gt;
&lt;p&gt;This method is actually a combination of the two above:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Set the working directory by following the exact same steps than for the user-friendly method (via the buttons)&lt;/li&gt;
&lt;li&gt;Copy the code executed in the console and paste it in the text editor (i.e., your script)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;I recommend this method for several reasons. First, you do not need to remember the &lt;code&gt;setwd()&lt;/code&gt; function. Second, you will not make typos in the path of your folder (path which can sometimes be quite long if you have folders inside folders). Third, when saving your script (which I assume you do otherwise you would lose all your work), you also save the actions you just made via the buttons. So when you reopen your script in the future, no matter what is the current directory, by executing your script (which now include the line of code for setting the working directory), you will at the same time specify the working directory you selected for this project.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;import-your-dataset&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Import your dataset&lt;/h1&gt;
&lt;p&gt;Now that you have transformed your Excel file into a CSV file and you have specified the folder containing your data by setting the working directory, you are now ready to actually import your dataset. Remind that there are two methods to import a file:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;in a user-friendly way&lt;/li&gt;
&lt;li&gt;via the text editor (see also below why it is my preferred option)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;No matter which method you choose, it is a good practice to first open your file in TextEdit (on Mac) or Notepad (on Windows) in order to see the raw data. If you open the file in Excel you will see the data already formatted and thus miss some important information needed for the importation. Below an example of raw data:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio_files/raw-data3.png&#34; alt=&#34;Example of raw data&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Example of raw data&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;There are a few things we need to look for in order to properly import our dataset:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Are the variables names present?&lt;/li&gt;
&lt;li&gt;How are the values separated? Comma, semicolon, whitespace, tab?&lt;/li&gt;
&lt;li&gt;Is the decimal a point or a comma?&lt;/li&gt;
&lt;li&gt;How are specified missing values? Empty cells, NA, null, O, other?&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&#34;user-friendly-way&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;User-friendly way&lt;/h2&gt;
&lt;p&gt;As shown below, simply click on the file &amp;gt; Import Dataset…&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio_files/import-data-rstudio.png&#34; alt=&#34;Import dataset in RStudio&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Import dataset in RStudio&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;A window which looks like this will open:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio_files/import-window-rstudio.png&#34; alt=&#34;Import window in RStudio&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Import window in RStudio&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;From this window, you can have a preview of your data, and more importantly, check whether your data seems to have been imported correctly. If your data have been correctly imported, you can click on “Import”. If this is not the case, you can change the import options at the bottom of the window (below the data preview) corresponding to the information you gathered when looking at the raw data. Below, the import options you will most likely use:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Name: set the name of your data set (default is the name of the file). Avoid special characters and long names (as you will have to type the name of your dataset several times). I personally rename my datasets with a generic name such as “dat”, others use “df” (for dataframe), “data”, or even “my_data”. You could use more explicit names such as “tennis_data” if you are using data on tennis matches for example. However, the main drawback with using specific names for datasets is that if, for instance, you want to reuse the code you created while analysing tennis data on other datasets, you will need to edit your code by replacing all occurrences of “tennis_data” by the name of your new dataset&lt;/li&gt;
&lt;li&gt;Skip: specify the number of top rows you want to skip (default is 0). Most of the time, 0 is fine. However, if your file contains some blank rows at the top (or information you want to disregard), set the number of rows to skip&lt;/li&gt;
&lt;li&gt;First Row as Names: specify whether the variables names are present or not (default is that variables names are present)&lt;/li&gt;
&lt;li&gt;Delimiter: the character which separate the values. From our raw data above, you can see that the delimiter is a comma (“,”). Change it to semicolon if your values are separated by “;”&lt;/li&gt;
&lt;li&gt;NA: how missing values are specified (default is empty cells). From our raw data above, you can see that missing values are simply empty cells, so leave NA to default or change it to “empty”. Change this option if missing values in your raw data are coded as “NA” or “0” (tip: do not code yourself missing values as “0”, otherwise you will not be able to distinguish the true zero values and the missing values)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;After changing the import options corresponding to your data, click on “Import”. You should now see your dataset in a new window and from there you can start analyzing your data.&lt;/p&gt;
&lt;p&gt;This user-friendly method has the advantage that you do not need to remember the code (see the next section for the entire code). However, the main drawback is that your import options will not be saved for a future usage so you will need to import your dataset manually each time you open RStudio.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;via-the-text-editor-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Via the text editor&lt;/h2&gt;
&lt;p&gt;Similarly to setting the working directory, I also recommend using the text editor instead of the user-friendly method for the simple reason that you can save your import options when using the text editor (and not when using the user-friendly method). Saving your import options in your script (thanks to a line of code) allows you to quickly import your dataset the exact same way without having to repeat all the necessary steps every time you import your dataset. The command to import a CSV file is &lt;code&gt;read.csv()&lt;/code&gt; (or &lt;code&gt;read.csv2()&lt;/code&gt; which is equivalent but with other default import options). Here is an example with the same file than in the user-friendly method:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;dat &amp;lt;- read.csv(
  file = &amp;quot;data.csv&amp;quot;,
  header = TRUE,
  sep = &amp;quot;,&amp;quot;,
  dec = &amp;quot;.&amp;quot;,
  stringsAsFactors = TRUE
)&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;dat &amp;lt;-&lt;/code&gt;: name of the dataset in RStudio. This means that after importation, I will need to refer to the dataset by calling &lt;code&gt;dat&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;file =&lt;/code&gt;: name of the file in the working directory. Do not forget “” around the name, the extension .csv at the end and the fact that RStudio is case sensitive (&lt;code&gt;&#34;Data.csv&#34;&lt;/code&gt; will give an &lt;a href=&#34;https://statsandr.com/blog/top-10-errors-in-r/&#34;&gt;error&lt;/a&gt;) and space sensitive inside “” (&lt;code&gt;&#34;data .csv&#34;&lt;/code&gt; will also throw an error). In our case the file is named “data.csv” so &lt;code&gt;file = &#34;data.csv&#34;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;header =&lt;/code&gt;: are variables names present? The default is &lt;code&gt;TRUE&lt;/code&gt;, change it to &lt;code&gt;FALSE&lt;/code&gt; if it is not the case in your dataset (&lt;code&gt;TRUE&lt;/code&gt; and &lt;code&gt;FALSE&lt;/code&gt; are always in capital letters, &lt;code&gt;true&lt;/code&gt; will not work!)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;sep =&lt;/code&gt;: separator. Equivalent to delimiter in the user-friendly method. Do not forget the ““. In our dataset the separator of the values is a comma so &lt;code&gt;sep = &#34;,&#34;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dec =&lt;/code&gt;: decimal. Do not forget the ““. In our dataset, the decimal for the numeric values is a point, so &lt;code&gt;dec = &#34;.&#34;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;stringsAsFactors =&lt;/code&gt;: should character vectors be converted to factors? The default option used to be &lt;code&gt;TRUE&lt;/code&gt;, but since R version 4.0.0 it is &lt;code&gt;FALSE&lt;/code&gt; by default. If all your character vectors are actually &lt;a href=&#34;https://statsandr.com/blog/variable-types-and-examples/#qualitative&#34;&gt;qualitative variables&lt;/a&gt; (so &lt;a href=&#34;https://statsandr.com/blog/data-types-in-r/#factor&#34;&gt;factors&lt;/a&gt; in R), set it to &lt;code&gt;TRUE&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;I do not write that missing values are coded as empty cells in my dataset because it is the default&lt;/li&gt;
&lt;li&gt;Last but not least, do not forget that the arguments are separated by a comma&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Other arguments exist, run &lt;code&gt;?read.csv&lt;/code&gt; to see all of them.&lt;/p&gt;
&lt;p&gt;After the importation you can check whether your data have been correctly imported by running &lt;code&gt;View(dat)&lt;/code&gt; where &lt;code&gt;dat&lt;/code&gt; is the name you chose for your data. A window, similar than for the user-friendly method, will display your data. Alternatively you can also run &lt;code&gt;head(dat)&lt;/code&gt; to see the first 6 rows and check that it corresponds to your Excel file. If something is not correct, edit the import options and check again. If your dataset has been correctly imported, you can now start analyzing your data. See other &lt;a href=&#34;https://statsandr.com/tags/R/&#34;&gt;articles on R&lt;/a&gt; if you want to learn how.&lt;/p&gt;
&lt;p&gt;The advantage of importing your dataset directly via the code in the text editor is that your import options will be saved for a future usage, preventing you from importing it manually every time you open your script. You will, however, need to remember the function &lt;code&gt;read.csv()&lt;/code&gt; (not the arguments since you can always check them in the help documentation).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;import-spss-.sav-files&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Import SPSS (.sav) files&lt;/h1&gt;
&lt;p&gt;Only Excel files are covered in details here. However, SPSS files (.sav) can also be read in R by using the following command:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(foreign)
dat &amp;lt;- read.spss(
  file = &amp;quot;filename.sav&amp;quot;,
  use.value.labels = TRUE,
  to.data.frame = TRUE
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;read.spss()&lt;/code&gt; function outputs a data table which retrieves all the characteristics of the .sav file, including the names given for the different levels of the categorical variables and the characteristics of the variables. If you need more information about this command, see the help documentation (&lt;code&gt;library(foreign)&lt;/code&gt; then &lt;code&gt;?read.spss&lt;/code&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 this article helped you to import an Excel file in RStudio. Now that your dataset is correctly imported, learn &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/&#34;&gt;how to manipulate it&lt;/a&gt; or how to perform &lt;a href=&#34;https://statsandr.com/blog/descriptive-statistics-in-r/&#34;&gt;descriptive statistics in R&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;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;I am aware that it is possible to import an Excel directly into R without converting it in a CSV file, with the &lt;code&gt;read_excel()&lt;/code&gt; function from the &lt;code&gt;{readxl}&lt;/code&gt; package for instance. However, CSV format is the standard and more importantly, importing a CSV does not require to &lt;a href=&#34;https://statsandr.com/blog/an-efficient-way-to-install-and-load-r-packages/&#34;&gt;install and load a package&lt;/a&gt; (which is sometimes confusing for beginners).&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>How to install R and RStudio?</title>
      <link>https://statsandr.com/blog/how-to-install-r-and-rstudio/</link>
      <pubDate>Tue, 17 Dec 2019 00:00:00 +0000</pubDate>
      
      <guid>https://statsandr.com/blog/how-to-install-r-and-rstudio/</guid>
      <description>

&lt;div id=&#34;TOC&#34;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#what-is-r-and-rstudio&#34; id=&#34;toc-what-is-r-and-rstudio&#34;&gt;What is R and RStudio?&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#r&#34; id=&#34;toc-r&#34;&gt;R&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#rstudio&#34; id=&#34;toc-rstudio&#34;&gt;RStudio&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#how-to-install-r-and-rstudio&#34; id=&#34;toc-how-to-install-r-and-rstudio&#34;&gt;How to install R and RStudio?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#the-main-components-of-rstudio&#34; id=&#34;toc-the-main-components-of-rstudio&#34;&gt;The main components of RStudio&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#examples-of-code&#34; id=&#34;toc-examples-of-code&#34;&gt;Examples of code&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;#calculator&#34; id=&#34;toc-calculator&#34;&gt;Calculator&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#comments&#34; id=&#34;toc-comments&#34;&gt;Comments&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#store-and-print-values&#34; id=&#34;toc-store-and-print-values&#34;&gt;Store and print values&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#vectors&#34; id=&#34;toc-vectors&#34;&gt;Vectors&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#matrices&#34; id=&#34;toc-matrices&#34;&gt;Matrices&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#generate-random-values&#34; id=&#34;toc-generate-random-values&#34;&gt;Generate random values&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#plot&#34; id=&#34;toc-plot&#34;&gt;Plot&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#conclusion&#34; id=&#34;toc-conclusion&#34;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio_files/0_vZhfBRnPyxoGbiQj.jpeg&#34; style=&#34;width:100.0%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note that this article is inspired from the lecture notes of Prof. Johan Segers and my personal notes as teaching assistant for his course entitled “Multivariate statistical analysis” given at UCLouvain.&lt;/em&gt;&lt;/p&gt;
&lt;div id=&#34;what-is-r-and-rstudio&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;What is R and RStudio?&lt;/h1&gt;
&lt;div id=&#34;r&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;R&lt;/h2&gt;
&lt;p&gt;The statistical program &lt;strong&gt;R&lt;/strong&gt; is nothing more than a programming language, mainly used for data manipulation and to perform statistical analyses. At the time of writing, this language is (one of) the leading program in statistics, although not the only programming language used by statisticians.&lt;/p&gt;
&lt;p&gt;In order to use R, we need two things:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a text editor in which to write our code&lt;/li&gt;
&lt;li&gt;a place to run this code&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;rstudio&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;RStudio&lt;/h2&gt;
&lt;p&gt;This is where RStudio comes handy.&lt;/p&gt;
&lt;p&gt;RStudio is an integrated development environment (IDE) for R. R and RStudio work together. R is a program that runs all your code, and RStudio is another program that allows you to control R in a more comfortable and friendly way. RStudio has the advantage of offering both a powerful text editor for writing your code and a place to run the code written in this editor.&lt;/p&gt;
&lt;p&gt;For these reasons, I highly recommend using RStudio instead of R. I use RStudio (and not R) on a daily basis and you will see that all &lt;a href=&#34;https://statsandr.com/blog/&#34;&gt;articles&lt;/a&gt; on this blog is written in RStudio.&lt;/p&gt;
&lt;p&gt;Note that RStudio requires the prior installation of the R software provided by CRAN in order to be able to function properly. Just installing RStudio on your personal computer is not enough. See the next section on how to install both.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;how-to-install-r-and-rstudio&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;How to install R and RStudio?&lt;/h1&gt;
&lt;p&gt;You can download R at &lt;a href=&#34;https://cran.r-project.org/mirrors.html&#34; target=&#34;_blank&#34;&gt;https://cran.r-project.org/mirrors.html&lt;/a&gt;. Select the CRAN mirror site closest to your country. If there are more than one links for your country, simply select one:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio_files/how-to-install-R-RStudio.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Select the CRAN mirror site closest to your country&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Select the CRAN mirror site closest to your country&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Then in the box labeled “Download and Install R” (located at the top), click on the link corresponding to your operating system (Windows, Mac or Linux):&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio_files/how-to-install-R-RStudio_2.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Click on the link corresponding to your operating system&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Click on the link corresponding to your operating system&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Now that R is installed on your computer, you can download RStudio. You can download the free version of RStudio (which is totally enough for most users, including me!) on their &lt;a href=&#34;https://www.rstudio.com/products/rstudio/download/#download&#34; target=&#34;_blank&#34;&gt;website&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;the-main-components-of-rstudio&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;The main components of RStudio&lt;/h1&gt;
&lt;p&gt;Now that both programs are installed on your computer, let’s dive into the main components of RStudio.&lt;/p&gt;
&lt;p&gt;By default, the RStudio window has three panes:&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;The console (red pane)&lt;/li&gt;
&lt;li&gt;The environment (green pane)&lt;/li&gt;
&lt;li&gt;Files, plots, help, etc. (blue pane)&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio_files/R%20Studio.png&#34; style=&#34;width:100.0%&#34; alt=&#34;RStudio window&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;RStudio window&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The console (red pane) is where you can execute your code (more information on the red and blue panes later). By default, the text editor does not open automatically. To open it, click on File &amp;gt; New File &amp;gt; R Script or click on the button representing a white sheet marked with a small green cross in the upper left corner, then on R Script:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio_files/open_text_editor.png&#34; style=&#34;width:100.0%&#34; alt=&#34;New R script in RStudio&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;New R script in RStudio&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;A new pane (in orange below), also known as the text editor, opens in which you will be able to write your code. The code will be executed and the results displayed in the console (red pane).&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio_files/text_editor.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Write and execute your code in RStudio&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Write and execute your code in RStudio&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Note that you can also write code in the console (red pane). However, I strongly recommend writing your code in the text editor (orange pane) because you can save the code written in the text editor (and thus execute it again later), while you cannot save the code written in the console.&lt;/p&gt;
&lt;p&gt;To execute code written in the text editor (orange pane), you have two options:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Type your code and then press the “Run” button (see below) or use the keyboard shortcut CTRL + Enter (cmd + Enter on Mac). &lt;strong&gt;Only the chunk&lt;/strong&gt; of code where your cursor is located will then be executed.&lt;/li&gt;
&lt;li&gt;Type your code and select in the text editor the part you want to execute and then press the “Run” button or use the keyboard shortcut CTRL + Enter (cmd + Enter on Mac). All the &lt;strong&gt;selected&lt;/strong&gt; code will be executed&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio_files/run.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Run code in RStudio&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Run code in RStudio&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;For example, try typing &lt;code&gt;1+1&lt;/code&gt; in the text editor and execute it by clicking on “Run” (or CTRL/cmd + Enter). You should see the result &lt;code&gt;2&lt;/code&gt; in the console, as shown in the screenshot below:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio_files/example%20of%20code%20executed%20in%20RStudio.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Example of code executed in RStudio&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Example of code executed in RStudio&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;The text editor and the console are the panes you will use most often. The two other panes (the blue and green panes introduced earlier) will however still be very useful when using RStudio.&lt;/p&gt;
&lt;p&gt;The environment (green pane) displays all values stored by RStudio. For example, if you type and execute the code &lt;code&gt;a = 1&lt;/code&gt;, RStudio will store the value &lt;code&gt;1&lt;/code&gt; for &lt;code&gt;a&lt;/code&gt;, as shown in the screenshot below:&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio_files/environment%20pane%20in%20RStudio2.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Environment pane in RStudio&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Environment pane in RStudio&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;This means that you can now perform any computations with &lt;code&gt;a&lt;/code&gt;, such that if you execute &lt;code&gt;a + 1&lt;/code&gt;, RStudio will render &lt;code&gt;2&lt;/code&gt; in the console. In this pane you can also see a tab with a history of the code executed and a button to import a dataset (more on &lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/&#34;&gt;importing a dataset in RStudio&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;The last pane (blue) is where you will find everything else such as your files, the plots, the packages, the help documentation, etc. I discuss about the Files tab in more detail &lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/&#34;&gt;here&lt;/a&gt; so let’s discuss about the other tabs:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Plot: where you will see the rendered plots. For instance, run &lt;code&gt;plot(1:10)&lt;/code&gt; and you should see it in this tab. If you plotted more than one plots, you can navigate between them by clicking on the arrows. You can open the plot in a new window by clicking on Zoom and export your plot by clicking on Export. Those buttons are located just under the Plot tab (see figure below)&lt;/li&gt;
&lt;li&gt;Packages: where you see all your installed packages. Only fundamental functionalities come with R. Everything else must be installed from packages. Remind that R is open source; everyone can write code and publish it as a package. You are then able to use this package (and all functions built inside this package) for free. Some packages are installed by default, all others must be installed by running &lt;code&gt;install.packages(&#34;name of the package&#34;)&lt;/code&gt; (do not forget &lt;code&gt;&#34;&#34;&lt;/code&gt; around the name of the package!). Once the package is installed, you must load the package and only after it has been loaded you can use all the functions it contains. To load a package, run &lt;code&gt;library(name of the package)&lt;/code&gt; (this time &lt;code&gt;&#34;&#34;&lt;/code&gt; around the name of the package are optional, but can still be used if you wish). You also have the possibility to install and load packages via the buttons under the Packages tab. For this, click on the button Install under Packages, type the name of the package you want to install and then click on Install. You will see that the code appears in the console. To load the package, find the package you want to load in the Packages window (you can use the search box), then click on the checkbox next to the name of the package. Again, the code is run in the console. See the figures below if needed. Note that you will need to install packages &lt;strong&gt;only once&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; but load packages &lt;strong&gt;each time&lt;/strong&gt; you open RStudio. Furthermore, note that an internet connection is required to install a package, while it is not required to load a package&lt;/li&gt;
&lt;li&gt;Help: documentation about all functions written for R. To access the help of a function, run &lt;code&gt;help(&#34;name of the function&#34;)&lt;/code&gt; or simply &lt;code&gt;?name of the function&lt;/code&gt;. For example, to see the help about the mean function, run &lt;code&gt;?mean&lt;/code&gt;. You can also press F1 while having your cursor on a function&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio_files/plot-buttons-rstudio.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Plot buttons in RStudio&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Plot buttons in RStudio&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio_files/install-packages-rstudio1.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Step 1: click on the Install button&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 1: click on the Install button&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio_files/install-packages-rstudio2.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Step 2: type the name of the package and click on Install&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 2: type the name of the package and click on Install&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;div class=&#34;float&#34;&gt;
&lt;img src=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio_files/install-packages-rstudio3.png&#34; style=&#34;width:100.0%&#34; alt=&#34;Step 3: load your package by clicking on the box next to the package’s name&#34; /&gt;
&lt;div class=&#34;figcaption&#34;&gt;Step 3: load your package by clicking on the box next to the package’s name&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;examples-of-code&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Examples of code&lt;/h1&gt;
&lt;p&gt;Now that you have installed R and RStudio and you know its main components, below are some examples of basic code.&lt;/p&gt;
&lt;p&gt;More advanced code and analyses are presented in &lt;a href=&#34;https://statsandr.com/tags/R/&#34;&gt;other articles about R&lt;/a&gt;, and in particular in this article about &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/&#34;&gt;data manipulation in R&lt;/a&gt;.&lt;/p&gt;
&lt;div id=&#34;calculator&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Calculator&lt;/h2&gt;
&lt;p&gt;Compute &lt;span class=&#34;math inline&#34;&gt;\(5*5\)&lt;/span&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;5 * 5&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 25&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Compute &lt;span class=&#34;math inline&#34;&gt;\(\frac{1}{\sqrt{50\pi}}\, e^{-\frac{(10 - 11)^2}{50}}\)&lt;/span&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;1 / sqrt(50 * pi) * exp(-(10 - 11)^2 / 50)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 0.07820854&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, some values like &lt;span class=&#34;math inline&#34;&gt;\(\pi\)&lt;/span&gt; are stored by default so you do not need to specify its value. Note that RStudio is case sensitive, but not space sensitive. This means that &lt;code&gt;pi&lt;/code&gt; is different than &lt;code&gt;Pi&lt;/code&gt; but &lt;code&gt;5*5&lt;/code&gt; gives the same result than &lt;code&gt;5 * 5&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;comments&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Comments&lt;/h2&gt;
&lt;p&gt;To add comments in your code, use &lt;code&gt;#&lt;/code&gt; before the code:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# A comment
# Another comment
1 + 1&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 2&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;store-and-print-values&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Store and print values&lt;/h2&gt;
&lt;p&gt;Note that in order to store a value inside an object, using &lt;code&gt;=&lt;/code&gt; or &lt;code&gt;&amp;lt;-&lt;/code&gt; is equivalent. I however recommend using &lt;code&gt;&amp;lt;-&lt;/code&gt; to follow the guidelines of R programming. You can name your objects (A and B in our case) as you like. However, it is recommended to use short and concise names (as you will most likely type them several times) and avoid special characters.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;A &amp;lt;- 5
B &amp;lt;- 6&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When storing values, RStudio does not display it on the console. To store a value AND print it in the console, use:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;(A &amp;lt;- 5)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 5&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;A &amp;lt;- 5
A&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 5&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;vectors&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Vectors&lt;/h2&gt;
&lt;p&gt;It is also possible to store more than one value inside an object via the function &lt;code&gt;c()&lt;/code&gt; (c stands for combine).&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;A &amp;lt;- c(1 / 2, -1, 0)
A&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1]  0.5 -1.0  0.0&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;matrices&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Matrices&lt;/h2&gt;
&lt;p&gt;Or create a matrix via &lt;code&gt;matrix()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;my_mat &amp;lt;- matrix(c(-1, 2, 0, 3), ncol = 2, nrow = 2)
my_mat&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      [,1] [,2]
## [1,]   -1    0
## [2,]    2    3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can access the help of this function via &lt;code&gt;?matrix&lt;/code&gt; or &lt;code&gt;help(&#34;matrix&#34;)&lt;/code&gt;. Note that inside a function, you can have multiple arguments separated by a comma. Inside &lt;code&gt;matrix()&lt;/code&gt;, the first argument is the vector &lt;code&gt;c(-1, 2, 0, 3)&lt;/code&gt;, the second is &lt;code&gt;ncol = 2&lt;/code&gt; and the third is &lt;code&gt;nrow = 2&lt;/code&gt;. For all functions in RStudio, you can specify an argument by its order inside the function or by the name of the argument. If you specify the name of the argument, the order does not matter anymore, so &lt;code&gt;matrix(c(-1, 2, 0, 3), ncol = 2, nrow = 2)&lt;/code&gt; is equivalent to &lt;code&gt;matrix(c(-1, 2, 0, 3), nrow = 2, ncol = 2)&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;my_mat2 &amp;lt;- matrix(c(-1, 2, 0, 3), nrow = 2, ncol = 2)
my_mat2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      [,1] [,2]
## [1,]   -1    0
## [2,]    2    3&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;my_mat == my_mat2 # is my_mat equal to my_mat2?&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      [,1] [,2]
## [1,] TRUE TRUE
## [2,] TRUE TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;generate-random-values&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Generate random values&lt;/h2&gt;
&lt;p&gt;To generate 10 values based on 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; with mean &lt;span class=&#34;math inline&#34;&gt;\(\mu = 400\)&lt;/span&gt; and standard deviation &lt;span class=&#34;math inline&#34;&gt;\(\sigma = 10\)&lt;/span&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;my_vec &amp;lt;- rnorm(10, mean = 400, sd = 10)
# Display only the first 5 values:
head(my_vec, 5)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 413.7096 394.3530 403.6313 406.3286 404.0427&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Display only the last 5 values:
tail(my_vec, 5)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 398.9388 415.1152 399.0534 420.1842 399.3729&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You will have different values than mine due to the fact that they are randomly generated. If you want to make sure to have always the same random values, use &lt;code&gt;set.seed()&lt;/code&gt; (with any numeric inside the brackets). For instance, with the following code, you should have the exact same values, no matter where and when you run it:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(42)
rnorm(3, mean = 10, sd = 2)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 12.741917  8.870604 10.726257&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;plot&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Plot&lt;/h2&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(my_vec,
  type = &amp;quot;l&amp;quot;, # &amp;quot;l&amp;quot; stands for line
  main = &amp;quot;Plot title&amp;quot;,
  ylab = &amp;quot;Y-axis label&amp;quot;,
  xlab = &amp;quot;X-axis label&amp;quot;
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://statsandr.com/blog/how-to-install-r-and-rstudio_files/figure-html/unnamed-chunk-12-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;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 install R and RStudio.&lt;/p&gt;
&lt;p&gt;This is only a very limited introduction to the possibilities of RStudio. If you want to learn more, I recommend that you read other &lt;a href=&#34;https://statsandr.com/tags/R/&#34;&gt;articles related to R&lt;/a&gt;, starting with &lt;a href=&#34;https://statsandr.com/blog/how-to-import-an-excel-file-in-rstudio/&#34;&gt;how to import an Excel file&lt;/a&gt; or &lt;a href=&#34;https://statsandr.com/blog/data-manipulation-in-r/&#34;&gt;how to manipulate a dataset 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 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;Actually you will need to reinstall your packages for each new R update. However, if you work on the same R version, you need to install your packages only once but load them everytime you open RStudio.&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>
    
  </channel>
</rss>