<?xml version="1.0" encoding="UTF-8" ?>
<!-- RSS generated by PHPBoost on Sun, 17 May 2026 11:03:56 +0200 -->

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Easy Guides]]></title>
		<atom:link href="https://www.sthda.com/english/syndication/rss/wiki/44" rel="self" type="application/rss+xml"/>
		<link>https://www.sthda.com</link>
		<description><![CDATA[Last articles of the category: Comparing Means in R]]></description>
		<copyright>(C) 2005-2026 PHPBoost</copyright>
		<language>en</language>
		<generator>PHPBoost</generator>
		
		
		<item>
			<title><![CDATA[Kruskal-Wallis Test in R]]></title>
			<link>https://www.sthda.com/english/wiki/kruskal-wallis-test-in-r</link>
			<guid>https://www.sthda.com/english/wiki/kruskal-wallis-test-in-r</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#what-is-kruskal-wallis-test">What is Kruskal-Wallis test?</a></li>
<li><a href="#visualize-your-data-and-compute-kruskal-wallis-test-in-r">Visualize your data and compute Kruskal-Wallis test in R</a><ul>
<li><a href="#import-your-data-into-r">Import your data into R</a></li>
<li><a href="#check-your-data">Check your data</a></li>
<li><a href="#visualize-the-data-using-box-plots">Visualize the data using box plots</a></li>
<li><a href="#compute-kruskal-wallis-test">Compute Kruskal-Wallis test</a></li>
<li><a href="#interpret">Interpret</a></li>
<li><a href="#multiple-pairwise-comparison-between-groups">Multiple pairwise-comparison between groups</a></li>
</ul></li>
<li><a href="#see-also">See also</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>

<div id="what-is-kruskal-wallis-test" class="section level1">
<h1>What is Kruskal-Wallis test?</h1>
<br/>
<div class="block">
<strong>Kruskal-Wallis test</strong> by rank is a <strong>non-parametric alternative</strong> to <a href="https://www.sthda.com/english/english/wiki/one-way-anova-test-in-r">one-way <strong>ANOVA test</strong></a>, which extends the <a href="https://www.sthda.com/english/english/wiki/unpaired-two-samples-wilcoxon-test-in-r">two-samples Wilcoxon test</a> in the situation where there are more than two groups. It’s recommended when the assumptions of one-way ANOVA test are not met. This tutorial describes how to compute Kruskal-Wallis test in <strong>R</strong> software.
</div>
<p><br/></p>
<p><br/> <img src="https://www.sthda.com/english/sthda/RDoc/images/kruskal-wallis-test.png" alt="Kruskal Wallis Test" /> <br/></p>
</div>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/pqs3" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/r-statistics-for-comparing-means.png" /><br/>
     Practical Statistics in R for Comparing Groups: Numerical Variables
      </a>
</div>
<div class="spacer"></div>
<div id="visualize-your-data-and-compute-kruskal-wallis-test-in-r" class="section level1">
<h1>Visualize your data and compute Kruskal-Wallis test in R</h1>
<div id="import-your-data-into-r" class="section level2">
<h2>Import your data into R</h2>
<ol style="list-style-type: decimal">
<li><p><strong>Prepare your data</strong> as specified here: <a href="https://www.sthda.com/english/english/wiki/best-practices-for-preparing-your-data-set-for-r">Best practices for preparing your data set for R</a></p></li>
<li><p><strong>Save your data</strong> in an external .txt tab or .csv files</p></li>
<li><p><strong>Import your data into R</strong> as follow:</p></li>
</ol>
<pre class="r"><code># If .txt tab file, use this
my_data <- read.delim(file.choose())
# Or, if .csv file, use this
my_data <- read.csv(file.choose())</code></pre>
<p>Here, we’ll use the built-in R data set named <em>PlantGrowth</em>. It contains the weight of plants obtained under a control and two different treatment conditions.</p>
<pre class="r"><code>my_data <- PlantGrowth</code></pre>
</div>
<div id="check-your-data" class="section level2">
<h2>Check your data</h2>
<pre class="r"><code># print the head of the file
head(my_data)</code></pre>
<pre><code>  weight group
1   4.17  ctrl
2   5.58  ctrl
3   5.18  ctrl
4   6.11  ctrl
5   4.50  ctrl
6   4.61  ctrl</code></pre>
<p><span class="notice">In R terminology, the column “group” is called factor and the different categories (“ctr”, “trt1”, “trt2”) are named factor levels. <strong>The levels are ordered alphabetically</strong>.</span></p>
<pre class="r"><code># Show the group levels
levels(my_data$group)</code></pre>
<pre><code>[1] "ctrl" "trt1" "trt2"</code></pre>
<p>If the levels are not automatically in the correct order, re-order them as follow:</p>
<pre class="r"><code>my_data$group <- ordered(my_data$group,
                         levels = c("ctrl", "trt1", "trt2"))</code></pre>
<p><span class="warning">It’s possible to compute summary statistics by groups. The dplyr package can be used.</span></p>
<ul>
<li>To install <strong>dplyr</strong> package, type this:</li>
</ul>
<pre class="r"><code>install.packages("dplyr")</code></pre>
<ul>
<li>Compute summary statistics by groups:</li>
</ul>
<pre class="r"><code>library(dplyr)
group_by(my_data, group) %>%
  summarise(
    count = n(),
    mean = mean(weight, na.rm = TRUE),
    sd = sd(weight, na.rm = TRUE),
    median = median(weight, na.rm = TRUE),
    IQR = IQR(weight, na.rm = TRUE)
  )</code></pre>
<pre><code>Source: local data frame [3 x 6]
   group count  mean        sd median    IQR
  (fctr) (int) (dbl)     (dbl)  (dbl)  (dbl)
1   ctrl    10 5.032 0.5830914  5.155 0.7425
2   trt1    10 4.661 0.7936757  4.550 0.6625
3   trt2    10 5.526 0.4425733  5.435 0.4675</code></pre>
</div>
<div id="visualize-the-data-using-box-plots" class="section level2">
<h2>Visualize the data using box plots</h2>
<ul>
<li><p>To use R base graphs read this: <a href="https://www.sthda.com/english/english/wiki/r-base-graphs">R base graphs</a>. Here, we’ll use the <a href="https://www.sthda.com/english/english/wiki/ggpubr-r-package-ggplot2-based-publication-ready-plots"><strong>ggpubr</strong> R package</a> for an easy ggplot2-based data visualization.</p></li>
<li><p>Install the latest version of ggpubr from GitHub as follow (recommended):</p></li>
</ul>
<pre class="r"><code># Install
if(!require(devtools)) install.packages("devtools")
devtools::install_github("kassambara/ggpubr")</code></pre>
<ul>
<li>Or, install from CRAN as follow:</li>
</ul>
<pre class="r"><code>install.packages("ggpubr")</code></pre>
<ul>
<li>Visualize your data with ggpubr:</li>
</ul>
<pre class="r"><code># Box plots
# ++++++++++++++++++++
# Plot weight by group and color by group
library("ggpubr")
ggboxplot(my_data, x = "group", y = "weight", 
          color = "group", palette = c("#00AFBB", "#E7B800", "#FC4E07"),
          order = c("ctrl", "trt1", "trt2"),
          ylab = "Weight", xlab = "Treatment")</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/kruskal-wallis-test-box-plot-1.png" alt="Kruskal-Wallis Test in R" width="384" style="margin-bottom:10px;" />
<p class="caption">
Kruskal-Wallis Test in R
</p>
</div>
<pre class="r"><code># Mean plots
# ++++++++++++++++++++
# Plot weight by group
# Add error bars: mean_se
# (other values include: mean_sd, mean_ci, median_iqr, ....)
library("ggpubr")
ggline(my_data, x = "group", y = "weight", 
       add = c("mean_se", "jitter"), 
       order = c("ctrl", "trt1", "trt2"),
       ylab = "Weight", xlab = "Treatment")</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/kruskal-wallis-test-box-plot-2.png" alt="Kruskal-Wallis Test in R" width="384" style="margin-bottom:10px;" />
<p class="caption">
Kruskal-Wallis Test in R
</p>
</div>
</div>
<div id="compute-kruskal-wallis-test" class="section level2">
<h2>Compute Kruskal-Wallis test</h2>
<p><span class="question">We want to know if there is any significant difference between the average weights of plants in the 3 experimental conditions.</span></p>
<p>The test can be performed using the function <strong>kruskal.test</strong>() as follow:</p>
<pre class="r"><code>kruskal.test(weight ~ group, data = my_data)</code></pre>
<pre><code>
    Kruskal-Wallis rank sum test
data:  weight by group
Kruskal-Wallis chi-squared = 7.9882, df = 2, p-value = 0.01842</code></pre>
</div>
<div id="interpret" class="section level2">
<h2>Interpret</h2>
<p>As the p-value is less than the significance level 0.05, we can conclude that there are significant differences between the treatment groups.</p>
</div>
<div id="multiple-pairwise-comparison-between-groups" class="section level2">
<h2>Multiple pairwise-comparison between groups</h2>
<p>From the output of the Kruskal-Wallis test, we know that there is a significant difference between groups, but we don’t know which pairs of groups are different.</p>
<p>It’s possible to use the function <strong>pairwise.wilcox.test</strong>() to calculate pairwise comparisons between group levels with corrections for multiple testing.</p>
<pre class="r"><code>pairwise.wilcox.test(PlantGrowth$weight, PlantGrowth$group,
                 p.adjust.method = "BH")</code></pre>
<pre><code>
    Pairwise comparisons using Wilcoxon rank sum test 
data:  PlantGrowth$weight and PlantGrowth$group 
     ctrl  trt1 
trt1 0.199 -    
trt2 0.095 0.027
P value adjustment method: BH </code></pre>
<p><span class="success">The pairwise comparison shows that, only trt1 and trt2 are significantly different (p < 0.05).</span></p>
</div>
</div>
<div id="see-also" class="section level1">
<h1>See also</h1>
<ul>
<li>Analysis of variance (ANOVA, parametric):
<ul>
<li><a href="https://www.sthda.com/english/english/wiki/one-way-anova-test-in-r">One-Way ANOVA Test in R</a></li>
<li><a href="https://www.sthda.com/english/english/wiki/two-way-anova-test-in-r">Two-Way ANOVA Test in R</a></li>
<li><a href="https://www.sthda.com/english/english/wiki/manova-test-in-r-multivariate-analysis-of-variance">MANOVA Test in R: Multivariate Analysis of Variance</a></li>
</ul></li>
</ul>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.2.4). </span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 08:35:22 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[MANOVA Test in R: Multivariate Analysis of Variance]]></title>
			<link>https://www.sthda.com/english/wiki/manova-test-in-r-multivariate-analysis-of-variance</link>
			<guid>https://www.sthda.com/english/wiki/manova-test-in-r-multivariate-analysis-of-variance</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#what-is-manova-test">What is MANOVA test?</a></li>
<li><a href="#assumptions-of-manova">Assumptions of MANOVA</a></li>
<li><a href="#interpretation-of-manova">Interpretation of MANOVA</a></li>
<li><a href="#compute-manova-in-r">Compute MANOVA in R</a><ul>
<li><a href="#import-your-data-into-r">Import your data into R</a></li>
<li><a href="#check-your-data">Check your data</a></li>
<li><a href="#compute-manova-test">Compute MANOVA test</a></li>
</ul></li>
<li><a href="#see-also">See also</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<div id="what-is-manova-test" class="section level1">
<h1>What is MANOVA test?</h1>
<br/>
<div class="block">
In the situation where there multiple response variables you can test them simultaneously using a <strong>multivariate analysis of variance</strong> (<strong>MANOVA</strong>). This article describes how to compute <strong>manova</strong> in R.
</div>
<p><br/></p>
<p>For example, we may conduct an experiment where we give two treatments (A and B) to two groups of mice, and we are interested in the weight and height of mice. In that case, the weight and height of mice are two dependent variables, and our hypothesis is that both together are affected by the difference in treatment. A multivariate analysis of variance could be used to test this hypothesis.</p>
<p><br/> <img src="https://www.sthda.com/english/sthda/RDoc/images/manova-test.png" alt="MANOVA Test" /> <br/></p>
</div>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/pqs3" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/r-statistics-for-comparing-means.png" /><br/>
     Practical Statistics in R for Comparing Groups: Numerical Variables
      </a>
</div>
<div class="spacer"></div>
<div id="assumptions-of-manova" class="section level1">
<h1>Assumptions of MANOVA</h1>
<p>MANOVA can be used in certain conditions:</p>
<ul>
<li><p>The dependent variables should be normally distribute within groups. The R function <strong>mshapiro.test</strong>( )[in the <strong>mvnormtest</strong> package] can be used to perform the Shapiro-Wilk test for multivariate normality. This is useful in the case of MANOVA, which assumes <strong>multivariate normality</strong>.</p></li>
<li><p>Homogeneity of variances across the range of predictors.</p></li>
<li><p>Linearity between all pairs of dependent variables, all pairs of covariates, and all dependent variable-covariate pairs in each cell</p></li>
</ul>
</div>
<div id="interpretation-of-manova" class="section level1">
<h1>Interpretation of MANOVA</h1>
<p>If the global multivariate test is significant, we conclude that the corresponding effect (treatment) is significant.
In that case, the next question is to determine if the treatment affects only the weight, only the height or both. In other words, we want to identify the specific dependent variables that contributed to the significant global effect.</p>
<p>To answer this question, we can use one-way ANOVA (or univariate ANOVA) to examine separately each dependent variable.</p>
</div>
<div id="compute-manova-in-r" class="section level1">
<h1>Compute MANOVA in R</h1>
<div id="import-your-data-into-r" class="section level2">
<h2>Import your data into R</h2>
<ol style="list-style-type: decimal">
<li><p><strong>Prepare your data</strong> as specified here: [url=/wiki/best-practices-for-preparing-your-data-set-for-r]Best practices for preparing your data set for R[/url]</p></li>
<li><p><strong>Save your data</strong> in an external .txt tab or .csv files</p></li>
<li><p><strong>Import your data into R</strong> as follow:</p></li>
</ol>
<pre class="r"><code># If .txt tab file, use this
my_data <- read.delim(file.choose())
# Or, if .csv file, use this
my_data <- read.csv(file.choose())</code></pre>
<p>Here, we’ll use iris data set:</p>
<pre class="r"><code># Store the data in the variable my_data
my_data <- iris</code></pre>
</div>
<div id="check-your-data" class="section level2">
<h2>Check your data</h2>
<p>The R code below display a random sample of our data using the function <strong>sample_n</strong>()[in <strong>dplyr</strong> package]. First, install dplyr if you don’t have it:</p>
<pre class="r"><code>install.packages("dplyr")</code></pre>
<pre class="r"><code># Show a random sample
set.seed(1234)
dplyr::sample_n(my_data, 10)</code></pre>
<pre><code>    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
94           5.0         2.3          3.3         1.0 versicolor
91           5.5         2.6          4.4         1.2 versicolor
93           5.8         2.6          4.0         1.2 versicolor
127          6.2         2.8          4.8         1.8  virginica
150          5.9         3.0          5.1         1.8  virginica
2            4.9         3.0          1.4         0.2     setosa
34           5.5         4.2          1.4         0.2     setosa
96           5.7         3.0          4.2         1.2 versicolor
74           6.1         2.8          4.7         1.2 versicolor
98           6.2         2.9          4.3         1.3 versicolor</code></pre>
<p><span class="question">Question: We want to know if there is any significant difference, in <em>sepal</em> and <em>petal</em> length, between the different species.</span></p>
</div>
<div id="compute-manova-test" class="section level2">
<h2>Compute MANOVA test</h2>
<p>The function <strong>manova</strong>() can be used as follow:</p>
<pre class="r"><code>sepl <- iris$Sepal.Length
petl <- iris$Petal.Length
# MANOVA test
res.man <- manova(cbind(Sepal.Length, Petal.Length) ~ Species, data = iris)
summary(res.man)</code></pre>
<pre><code>           Df Pillai approx F num Df den Df    Pr(>F)    
Species     2 0.9885   71.829      4    294 < 2.2e-16 ***
Residuals 147                                            
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</code></pre>
<pre class="r"><code># Look to see which differ
summary.aov(res.man)</code></pre>
<pre><code> Response Sepal.Length :
             Df Sum Sq Mean Sq F value    Pr(>F)    
Species       2 63.212  31.606  119.26 < 2.2e-16 ***
Residuals   147 38.956   0.265                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
 Response Petal.Length :
             Df Sum Sq Mean Sq F value    Pr(>F)    
Species       2 437.10 218.551  1180.2 < 2.2e-16 ***
Residuals   147  27.22   0.185                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</code></pre>
<p><span class="success">From the output above, it can be seen that the two variables are highly significantly different among Species.</span></p>
</div>
</div>
<div id="see-also" class="section level1">
<h1>See also</h1>
<ul>
<li>Analysis of variance (ANOVA, parametric):
<ul>
<li>[url=/wiki/one-way-anova-test-in-r]One-Way ANOVA Test in R[/url]</li>
<li>[url=/wiki/two-way-anova-test-in-r]Two-Way ANOVA Test in R[/url]</li>
</ul></li>
<li>[url=/wiki/kruskal-wallis-test-in-r]Kruskal-Wallis Test in R (non parametric alternative to one-way ANOVA)[/url]</li>
</ul>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.2.4). </span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 08:33:54 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Paired Samples Wilcoxon Test in R]]></title>
			<link>https://www.sthda.com/english/wiki/paired-samples-wilcoxon-test-in-r</link>
			<guid>https://www.sthda.com/english/wiki/paired-samples-wilcoxon-test-in-r</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#visualize-your-data-and-compute-paired-samples-wilcoxon-test-in-r">Visualize your data and compute paired samples Wilcoxon test in R</a><ul>
<li><a href="#r-function">R function</a></li>
<li><a href="#import-your-data-into-r">Import your data into R</a></li>
<li><a href="#check-your-data">Check your data</a></li>
<li><a href="#visualize-your-data-using-box-plots">Visualize your data using box plots</a></li>
<li><a href="#compute-paired-sample-wilcoxon-test">Compute paired-sample Wilcoxon test</a></li>
</ul></li>
<li><a href="#online-paired-sample-wilcoxon-test-calculator">Online paired-sample Wilcoxon test calculator</a></li>
<li><a href="#see-also">See also</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<p>The <strong>paired samples Wilcoxon test</strong> (also known as <strong>Wilcoxon signed-rank test</strong>) is a <strong>non-parametric</strong> alternative to paired t-test used to compare paired data. It’s used when your data are not normally distributed. This tutorial describes how to compute paired samples Wilcoxon test in <strong>R</strong>.</p>
<p><span class="error">Differences between paired samples should be distributed symmetrically around the median.</span></p>
<p><br/> <img src="https://www.sthda.com/english/sthda/RDoc/images/paired-samples-wilcoxon-test.png" alt="Paired samples wilcoxon test" /> <br/></p>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/pqs3" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/r-statistics-for-comparing-means.png" /><br/>
     Practical Statistics in R for Comparing Groups: Numerical Variables
      </a>
</div>
<div class="spacer"></div>

<div id="visualize-your-data-and-compute-paired-samples-wilcoxon-test-in-r" class="section level1">
<h1>Visualize your data and compute paired samples Wilcoxon test in R</h1>
<div id="r-function" class="section level2">
<h2>R function</h2>
<p>The R function <strong>wilcox.test</strong>() can be used as follow:</p>
<pre class="r"><code>wilcox.test(x, y, paired = TRUE, alternative = "two.sided")</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>x,y</strong>: numeric vectors</li>
<li><strong>paired</strong>: a logical value specifying that we want to compute a paired Wilcoxon test</li>
<li><strong>alternative</strong>: the alternative hypothesis. Allowed value is one of “two.sided” (default), “greater” or “less”.</li>
</ul>
</div>
<p><br/></p>
</div>
<div id="import-your-data-into-r" class="section level2">
<h2>Import your data into R</h2>
<ol style="list-style-type: decimal">
<li><p><strong>Prepare your data</strong> as specified here: <a href="https://www.sthda.com/english/english/wiki/best-practices-for-preparing-your-data-set-for-r">Best practices for preparing your data set for R</a></p></li>
<li><p><strong>Save your data</strong> in an external .txt tab or .csv files</p></li>
<li><p><strong>Import your data into R</strong> as follow:</p></li>
</ol>
<pre class="r"><code># If .txt tab file, use this
my_data <- read.delim(file.choose())
# Or, if .csv file, use this
my_data <- read.csv(file.choose())</code></pre>
<p>Here, we’ll use an example data set, which contains the weight of 10 mice before and after the treatment.</p>
<pre class="r"><code># Data in two numeric vectors
# ++++++++++++++++++++++++++
# Weight of the mice before treatment
before <-c(200.1, 190.9, 192.7, 213, 241.4, 196.9, 172.2, 185.5, 205.2, 193.7)
# Weight of the mice after treatment
after <-c(392.9, 393.2, 345.1, 393, 434, 427.9, 422, 383.9, 392.3, 352.2)
# Create a data frame
my_data <- data.frame( 
                group = rep(c("before", "after"), each = 10),
                weight = c(before,  after)
                )</code></pre>
<p><span class="question">We want to know, if there is any significant difference in the median weights before and after treatment?</span></p>
</div>
<div id="check-your-data" class="section level2">
<h2>Check your data</h2>
<pre class="r"><code># Print all data
print(my_data)</code></pre>
<pre><code>    group weight
1  before  200.1
2  before  190.9
3  before  192.7
4  before  213.0
5  before  241.4
6  before  196.9
7  before  172.2
8  before  185.5
9  before  205.2
10 before  193.7
11  after  392.9
12  after  393.2
13  after  345.1
14  after  393.0
15  after  434.0
16  after  427.9
17  after  422.0
18  after  383.9
19  after  392.3
20  after  352.2</code></pre>
<p>Compute summary statistics (median and inter-quartile range (IQR)) by groups using the dplyr package can be used.</p>
<ul>
<li>Install <strong>dplyr</strong> package:</li>
</ul>
<pre class="r"><code>install.packages("dplyr")</code></pre>
<ul>
<li>Compute summary statistics by groups:</li>
</ul>
<pre class="r"><code>library("dplyr")
group_by(my_data, group) %>%
  summarise(
    count = n(),
    median = median(weight, na.rm = TRUE),
    IQR = IQR(weight, na.rm = TRUE)
  )</code></pre>
<pre><code>Source: local data frame [2 x 4]
   group count median    IQR
  (fctr) (int)  (dbl)  (dbl)
1  after    10 392.95 28.800
2 before    10 195.30 12.575</code></pre>
</div>
<div id="visualize-your-data-using-box-plots" class="section level2">
<h2>Visualize your data using box plots</h2>
<ul>
<li><p>To use R base graphs read this: <a href="https://www.sthda.com/english/english/wiki/r-base-graphs">R base graphs</a>. Here, we’ll use the <a href="https://www.sthda.com/english/english/wiki/ggpubr-r-package-ggplot2-based-publication-ready-plots"><strong>ggpubr</strong> R package</a> for an easy ggplot2-based data visualization.</p></li>
<li><p>Install the latest version of ggpubr from GitHub as follow (recommended):</p></li>
</ul>
<pre class="r"><code># Install
if(!require(devtools)) install.packages("devtools")
devtools::install_github("kassambara/ggpubr")</code></pre>
<ul>
<li>Or, install from CRAN as follow:</li>
</ul>
<pre class="r"><code>install.packages("ggpubr")</code></pre>
<ul>
<li>Visualize your data:</li>
</ul>
<pre class="r"><code># Plot weight by group and color by group
library("ggpubr")
ggboxplot(my_data, x = "group", y = "weight", 
          color = "group", palette = c("#00AFBB", "#E7B800"),
          order = c("before", "after"),
          ylab = "Weight", xlab = "Groups")</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/paired-sample-wilcoxon-test-box-plot-1.png" alt="Paired Samples Wilcoxon Test in R" width="336" style="margin-bottom:10px;" />
<p class="caption">
Paired Samples Wilcoxon Test in R
</p>
</div>
<p><span class="warning">Box plots show you the increase, but lose the paired information. You can use the function <strong>plot.paired</strong>() [in <strong>pairedData</strong> package] to plot paired data (“before - after” plot).</span></p>
<ul>
<li>Install pairedData package:</li>
</ul>
<pre class="r"><code>install.packages("PairedData")</code></pre>
<ul>
<li>Plot paired data:</li>
</ul>
<pre class="r"><code># Subset weight data before treatment
before <- subset(my_data,  group == "before", weight,
                 drop = TRUE)
# subset weight data after treatment
after <- subset(my_data,  group == "after", weight,
                 drop = TRUE)
# Plot paired data
library(PairedData)
pd <- paired(before, after)
plot(pd, type = "profile") + theme_bw()</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/paired-sample-wilcoxon-test-before-after-plot-1.png" alt="Paired Samples Wilcoxon Test in R" width="336" style="margin-bottom:10px;" />
<p class="caption">
Paired Samples Wilcoxon Test in R
</p>
</div>
</div>
<div id="compute-paired-sample-wilcoxon-test" class="section level2">
<h2>Compute paired-sample Wilcoxon test</h2>
<p><span class="question">Question : Is there any significant changes in the weights of mice before after treatment?</span></p>
<p><strong>1) Compute paired Wilcoxon test - Method 1</strong>: The data are saved in two different numeric vectors.</p>
<pre class="r"><code>res <- wilcox.test(before, after, paired = TRUE)
res</code></pre>
<pre><code>
    Wilcoxon signed rank test
data:  before and after
V = 0, p-value = 0.001953
alternative hypothesis: true location shift is not equal to 0</code></pre>
<p><strong>2) Compute paired Wilcoxon-test - Method 2</strong>: The data are saved in a data frame.</p>
<pre class="r"><code># Compute t-test
res <- wilcox.test(weight ~ group, data = my_data, paired = TRUE)
res</code></pre>
<pre><code>
    Wilcoxon signed rank test
data:  weight by group
V = 55, p-value = 0.001953
alternative hypothesis: true location shift is not equal to 0</code></pre>
<pre class="r"><code># print only the p-value
res$p.value</code></pre>
<pre><code>[1] 0.001953125</code></pre>
<p><span class="notice">As you can see, the two methods give the same results.</span></p>
<p><span class="success">The <strong>p-value</strong> of the test is 0.001953, which is less than the significance level alpha = 0.05. We can conclude that the median weight of the mice before treatment is significantly different from the median weight after treatment with a <strong>p-value</strong> = 0.001953.</span></p>
<br/>
<div class="notice">
<p>Note that:</p>
<ul>
<li>if you want to test whether the median weight before treatment is less than the median weight after treatment, type this:</li>
</ul>
<pre class="r"><code>wilcox.test(weight ~ group, data = my_data, paired = TRUE,
        alternative = "less")</code></pre>
<ul>
<li>Or, if you want to test whether the median weight before treatment is greater than the median weight after treatment, type this</li>
</ul>
<pre class="r"><code>wilcox.test(weight ~ group, data = my_data, paired = TRUE,
       alternative = "greater")</code></pre>
</div>
<p><br/></p>
</div>
</div>
<div id="online-paired-sample-wilcoxon-test-calculator" class="section level1">
<h1>Online paired-sample Wilcoxon test calculator</h1>
<p>You can perform <strong>paired-sample Wilcoxon test</strong>, <strong>online</strong>, without any installation by clicking the following link:</p>
<br/>
<div class="block">
<i class="fa - fa-cogs fa-4x valign_middle"></i> <a href="https://www.sthda.com/english/english/rsthda/paired-wilcoxon.php">Online paired-sample Wilcoxon test calculator</a>
</div>
<p><br/></p>
</div>
<div id="see-also" class="section level1">
<h1>See also</h1>
<p><a href="https://www.sthda.com/english/english/wiki/paired-samples-t-test-in-r">Paired Samples T-test (parametric)</a></p>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.2.4). </span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 08:32:19 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Unpaired Two-Samples Wilcoxon Test in R]]></title>
			<link>https://www.sthda.com/english/wiki/unpaired-two-samples-wilcoxon-test-in-r</link>
			<guid>https://www.sthda.com/english/wiki/unpaired-two-samples-wilcoxon-test-in-r</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#visualize-your-data-and-compute-wilcoxon-test-in-r">Visualize your data and compute Wilcoxon test in R</a><ul>
<li><a href="#r-function-to-compute-wilcoxon-test">R function to compute Wilcoxon test</a></li>
<li><a href="#import-your-data-into-r">Import your data into R</a></li>
<li><a href="#check-your-data">Check your data</a></li>
<li><a href="#visualize-your-data-using-box-plots">Visualize your data using box plots</a></li>
<li><a href="#compute-unpaired-two-samples-wilcoxon-test">Compute unpaired two-samples Wilcoxon test</a></li>
</ul></li>
<li><a href="#online-unpaired-two-samples-wilcoxon-test-calculator">Online unpaired two-samples Wilcoxon test calculator</a></li>
<li><a href="#see-also">See also</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<div class="block">
The <strong>unpaired two-samples Wilcoxon test</strong> (also known as <strong>Wilcoxon rank sum test</strong> or <strong>Mann-Whitney</strong> test) is a non-parametric alternative to the <a href="https://www.sthda.com/english/english/wiki/unpaired-two-samples-t-test-in-r">unpaired two-samples t-test</a>, which can be used to compare two independent groups of samples. It’s used when your data are not normally distributed.
</div>
<p><br/></p>
<p><br/> <img src="https://www.sthda.com/english/sthda/RDoc/images/unpaired-two-samples-wilcoxon-test.png" alt="Unpaired two-samples wilcoxon test" /> <br/></p>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/pqs3" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/r-statistics-for-comparing-means.png" /><br/>
     Practical Statistics in R for Comparing Groups: Numerical Variables
      </a>
</div>
<div class="spacer"></div>
<p><span class="success">This article describes how to compute two samples Wilcoxon test in R.</span></p>
<div id="visualize-your-data-and-compute-wilcoxon-test-in-r" class="section level1">
<h1>Visualize your data and compute Wilcoxon test in R</h1>
<div id="r-function-to-compute-wilcoxon-test" class="section level2">
<h2>R function to compute Wilcoxon test</h2>
<p>To perform two-samples Wilcoxon test comparing the means of two independent samples (x &amp; y), the R function <strong>wilcox.test</strong>() can be used as follow:</p>
<pre class="r"><code>wilcox.test(x, y, alternative = "two.sided")</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>x,y</strong>: numeric vectors</li>
<li><strong>alternative</strong>: the alternative hypothesis. Allowed value is one of “two.sided” (default), “greater” or “less”.</li>
</ul>
</div>
<p><br/></p>
</div>
<div id="import-your-data-into-r" class="section level2">
<h2>Import your data into R</h2>
<ol style="list-style-type: decimal">
<li><p><strong>Prepare your data</strong> as specified here: <a href="https://www.sthda.com/english/english/wiki/best-practices-for-preparing-your-data-set-for-r">Best practices for preparing your data set for R</a></p></li>
<li><p><strong>Save your data</strong> in an external .txt tab or .csv files</p></li>
<li><p><strong>Import your data into R</strong> as follow:</p></li>
</ol>
<pre class="r"><code># If .txt tab file, use this
my_data <- read.delim(file.choose())
# Or, if .csv file, use this
my_data <- read.csv(file.choose())</code></pre>
<p>Here, we’ll use an example data set, which contains the weight of 18 individuals (9 women and 9 men):</p>
<pre class="r"><code># Data in two numeric vectors
women_weight <- c(38.9, 61.2, 73.3, 21.8, 63.4, 64.6, 48.4, 48.8, 48.5)
men_weight <- c(67.8, 60, 63.4, 76, 89.4, 73.3, 67.3, 61.3, 62.4) 
# Create a data frame
my_data <- data.frame( 
                group = rep(c("Woman", "Man"), each = 9),
                weight = c(women_weight,  men_weight)
                )</code></pre>
<p><span class="question">We want to know, if the median women’s weight differs from the median men’s weight?</span></p>
</div>
<div id="check-your-data" class="section level2">
<h2>Check your data</h2>
<pre class="r"><code>print(my_data)</code></pre>
<pre><code>   group weight
1  Woman   38.9
2  Woman   61.2
3  Woman   73.3
4  Woman   21.8
5  Woman   63.4
6  Woman   64.6
7  Woman   48.4
8  Woman   48.8
9  Woman   48.5
10   Man   67.8
11   Man   60.0
12   Man   63.4
13   Man   76.0
14   Man   89.4
15   Man   73.3
16   Man   67.3
17   Man   61.3
18   Man   62.4</code></pre>
<p><span class="warning">It’s possible to compute <a href="https://www.sthda.com/english/english/wiki/descriptive-statistics-and-graphics">summary statistics</a> (median and interquartile range (IQR)) by groups. The dplyr package can be used.</span></p>
<ul>
<li>To install <strong>dplyr</strong> package, type this:</li>
</ul>
<pre class="r"><code>install.packages("dplyr")</code></pre>
<ul>
<li>Compute summary statistics by groups:</li>
</ul>
<pre class="r"><code>library(dplyr)
group_by(my_data, group) %>%
  summarise(
    count = n(),
    median = median(weight, na.rm = TRUE),
    IQR = IQR(weight, na.rm = TRUE)
  )</code></pre>
<pre><code>Source: local data frame [2 x 4]
   group count median   IQR
  (fctr) (int)  (dbl) (dbl)
1    Man     9   67.3  10.9
2  Woman     9   48.8  15.0</code></pre>
</div>
<div id="visualize-your-data-using-box-plots" class="section level2">
<h2>Visualize your data using box plots</h2>
<p>You can draw R base graphs as described at this link: <a href="https://www.sthda.com/english/english/wiki/r-base-graphs">R base graphs</a>. Here, we’ll use the <a href="https://www.sthda.com/english/english/wiki/ggpubr-r-package-ggplot2-based-publication-ready-plots"><strong>ggpubr</strong> R package</a> for an easy ggplot2-based data visualization</p>
<ul>
<li>Install the latest version of ggpubr from GitHub as follow (recommended):</li>
</ul>
<pre class="r"><code># Install
if(!require(devtools)) install.packages("devtools")
devtools::install_github("kassambara/ggpubr")</code></pre>
<ul>
<li>Or, install from CRAN as follow:</li>
</ul>
<pre class="r"><code>install.packages("ggpubr")</code></pre>
<ul>
<li>Visualize your data:</li>
</ul>
<pre class="r"><code># Plot weight by group and color by group
library("ggpubr")
ggboxplot(my_data, x = "group", y = "weight", 
          color = "group", palette = c("#00AFBB", "#E7B800"),
          ylab = "Weight", xlab = "Groups")</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/unpaired-two-samples-wilcoxon-test-box-plot-1.png" alt="Unpaired Two-Samples Wilcoxon Test in R" width="336" style="margin-bottom:10px;" />
<p class="caption">
Unpaired Two-Samples Wilcoxon Test in R
</p>
</div>
</div>
<div id="compute-unpaired-two-samples-wilcoxon-test" class="section level2">
<h2>Compute unpaired two-samples Wilcoxon test</h2>
<p><span class="question">Question : Is there any significant difference between women and men weights?</span></p>
<p><strong>1) Compute two-samples Wilcoxon test - Method 1</strong>: The data are saved in two different numeric vectors.</p>
<pre class="r"><code>res <- wilcox.test(women_weight, men_weight)
res</code></pre>
<pre><code>
    Wilcoxon rank sum test with continuity correction
data:  women_weight and men_weight
W = 15, p-value = 0.02712
alternative hypothesis: true location shift is not equal to 0</code></pre>
<p><span class="warning">It will give a warning message, saying that “cannot compute exact p-value with tie”. It comes from the assumption of a Wilcoxon test that the responses are continuous. You can suppress this message by adding another argument <strong>exact = FALSE</strong>, but the result will be the same.</span></p>
<p><strong>2) Compute two-samples Wilcoxon test - Method 2</strong>: The data are saved in a data frame.</p>
<pre class="r"><code>res <- wilcox.test(weight ~ group, data = my_data,
                   exact = FALSE)
res</code></pre>
<pre><code>
    Wilcoxon rank sum test with continuity correction
data:  weight by group
W = 66, p-value = 0.02712
alternative hypothesis: true location shift is not equal to 0</code></pre>
<pre class="r"><code># Print the p-value only
res$p.value</code></pre>
<pre><code>[1] 0.02711657</code></pre>
<p><span class="notice">As you can see, the two methods give the same results.</span></p>
<p><span class="success">The <strong>p-value</strong> of the test is 0.02712, which is less than the significance level alpha = 0.05. We can conclude that men’s median weight is significantly different from women’s median weight with a <strong>p-value</strong> = 0.02712.</span></p>
<br/>
<div class="notice">
<p>Note that:</p>
<ul>
<li>if you want to test whether the median men’s weight is less than the median women’s weight, type this:</li>
</ul>
<pre class="r"><code>wilcox.test(weight ~ group, data = my_data, 
        exact = FALSE, alternative = "less")</code></pre>
<ul>
<li>Or, if you want to test whether the median men’s weight is greater than the median women’s weight, type this</li>
</ul>
<pre class="r"><code>wilcox.test(weight ~ group, data = my_data,
        exact = FALSE, alternative = "greater")</code></pre>
</div>
<p><br/></p>
</div>
</div>
<div id="online-unpaired-two-samples-wilcoxon-test-calculator" class="section level1">
<h1>Online unpaired two-samples Wilcoxon test calculator</h1>
<p>You can perform unpaired <strong>two-samples Wilcoxon test</strong>, <strong>online</strong>, without any installation by clicking the following link:</p>
<br/>
<div class="block">
<i class="fa - fa-cogs fa-4x valign_middle"></i> <a href="https://www.sthda.com/english/english/rsthda/unpaired-wilcoxon.php">Online two-samples Wilcoxon test calculator</a>
</div>
<p><br/></p>
</div>
<div id="see-also" class="section level1">
<h1>See also</h1>
<ul>
<li>Compare one-sample mean to a standard known mean
<ul>
<li><a href="https://www.sthda.com/english/english/wiki/one-sample-t-test-in-r">One-Sample T-test (parametric)</a></li>
<li><a href="https://www.sthda.com/english/english/wiki/one-sample-wilcoxon-signed-rank-test-in-r">One-Sample Wilcoxon Test (non-parametric)</a></li>
</ul></li>
<li>Compare the means of two independent groups
<ul>
<li><a href="https://www.sthda.com/english/english/wiki/unpaired-two-samples-t-test-in-r">Unpaired Two Samples T-test (parametric)</a></li>
</ul></li>
</ul>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.2.4). </span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 08:30:29 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Unpaired Two-Samples T-test in R]]></title>
			<link>https://www.sthda.com/english/wiki/unpaired-two-samples-t-test-in-r</link>
			<guid>https://www.sthda.com/english/wiki/unpaired-two-samples-t-test-in-r</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#what-is-unpaired-two-samples-t-test">What is unpaired two-samples t-test?</a></li>
<li><a href="#research-questions-and-statistical-hypotheses">Research questions and statistical hypotheses</a></li>
<li><a href="#formula-of-unpaired-two-samples-t-test">Formula of unpaired two-samples t-test</a></li>
<li><a href="#visualize-your-data-and-compute-unpaired-two-samples-t-test-in-r">Visualize your data and compute unpaired two-samples t-test in R</a><ul>
<li><a href="#install-ggpubr-r-package-for-data-visualization">Install ggpubr R package for data visualization</a></li>
<li><a href="#r-function-to-compute-unpaired-two-samples-t-test">R function to compute unpaired two-samples t-test</a></li>
<li><a href="#import-your-data-into-r">Import your data into R</a></li>
<li><a href="#check-your-data">Check your data</a></li>
<li><a href="#visualize-your-data-using-box-plots">Visualize your data using box plots</a></li>
<li><a href="#preleminary-test-to-check-independent-t-test-assumptions">Preleminary test to check independent t-test assumptions</a></li>
<li><a href="#compute-unpaired-two-samples-t-test">Compute unpaired two-samples t-test</a></li>
<li><a href="#interpretation-of-the-result">Interpretation of the result</a></li>
<li><a href="#access-to-the-values-returned-by-t.test-function">Access to the values returned by t.test() function</a></li>
</ul></li>
<li><a href="#online-unpaired-two-samples-t-test-calculator">Online unpaired two-samples t-test calculator</a></li>
<li><a href="#see-also">See also</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<div id="what-is-unpaired-two-samples-t-test" class="section level1">
<h1>What is unpaired two-samples t-test?</h1>
<br/>
<div class="block">
The <strong>unpaired two-samples t-test</strong> is used to compare the <strong>mean</strong> of two independent groups.
</div>
<p><br/></p>
<p>For example, suppose that we have measured the weight of 100 individuals: 50 women (group A) and 50 men (group B). We want to know if the mean weight of women (<span class="math">\(m_A\)</span>) is significantly different from that of men (<span class="math">\(m_B\)</span>).</p>
<p>In this case, we have two unrelated (i.e., independent or unpaired) groups of samples. Therefore, it’s possible to use an <strong>independent t-test</strong> to evaluate whether the means are different.</p>
<div class="error">
<p>Note that, unpaired two-samples t-test can be used only under certain conditions:</p>
<ul>
<li>when the two groups of samples (A and B), being compared, are <strong>normally distributed</strong>. This can be checked using <a href="https://www.sthda.com/english/english/wiki/normality-test-in-r"><strong>Shapiro-Wilk test</strong></a>.</li>
<li>and when the <strong>variances</strong> of the two groups are equal. This can be checked using <strong>F-test</strong>.</li>
</ul>
</div>
<p><br/></p>
<p><br/> <img src="https://www.sthda.com/english/sthda/RDoc/images/unpaired-two-samples-t-test.png" alt="Unpaired two-samples t-test" /> <br/></p>
<p><span class="success">This article describes the formula of the independent t-test and provides pratical examples in R.</span></p>
</div>

<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/pqs3" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/r-statistics-for-comparing-means.png" /><br/>
     Practical Statistics in R for Comparing Groups: Numerical Variables
      </a>
</div>
<div class="spacer"></div>

<div id="research-questions-and-statistical-hypotheses" class="section level1">
<h1>Research questions and statistical hypotheses</h1>
<p>Typical research questions are:</p>
<br/>
<div class="question">
<ol style="list-style-type: decimal">
<li>whether the mean of group A (<span class="math">\(m_A\)</span>) <em>is equal</em> to the mean of group B (<span class="math">\(m_B\)</span>)?</li>
<li>whether the mean of group A (<span class="math">\(m_A\)</span>) <em>is less than</em> the mean of group B (<span class="math">\(m_B\)</span>)?</li>
<li>whether the mean of group A (<span class="math">\(m_A\)</span>) <em>is greather than</em> the mean of group B (<span class="math">\(m_B\)</span>)?</li>
</ol>
</div>
<p><br/></p>
<p>In statistics, we can define the corresponding <em>null hypothesis</em> (<span class="math">\(H_0\)</span>) as follow:</p>
<ol style="list-style-type: decimal">
<li><span class="math">\(H_0: m_A = m_B\)</span></li>
<li><span class="math">\(H_0: m_A \leq m_B\)</span></li>
<li><span class="math">\(H_0: m_A \geq m_B\)</span></li>
</ol>
<p>The corresponding <em>alternative hypotheses</em> (<span class="math">\(H_a\)</span>) are as follow:</p>
<ol style="list-style-type: decimal">
<li><span class="math">\(H_a: m_A \ne m_B\)</span> (different)</li>
<li><span class="math">\(H_a: m_A > m_B\)</span> (greater)</li>
<li><span class="math">\(H_a: m_A < m_B\)</span> (less)</li>
</ol>
<div class="notice">
<p>Note that:</p>
<ul>
<li>Hypotheses 1) are called <strong>two-tailed tests</strong></li>
<li>Hypotheses 2) and 3) are called <strong>one-tailed tests</strong></li>
</ul>
</div>
</div>
<div id="formula-of-unpaired-two-samples-t-test" class="section level1">
<h1>Formula of unpaired two-samples t-test</h1>
<ol style="list-style-type: decimal">
<li><strong>Classical t-test</strong>:</li>
</ol>
<p><span class="warning">If the variance of the two groups are equivalent (<strong>homoscedasticity</strong>), the <strong>t-test value</strong>, comparing the two samples (<span class="math">\(A\)</span> and <span class="math">\(B\)</span>), can be calculated as follow.</span></p>
<p><span class="math">\[ 
t = \frac{m_A - m_B}{\sqrt{ \frac{S^2}{n_A} + \frac{S^2}{n_B} }} 
\]</span></p>
<p>where,</p>
<ul>
<li><span class="math">\(m_A\)</span> and <span class="math">\(m_B\)</span> represent the mean value of the group A and B, respectively.</li>
<li><span class="math">\(n_A\)</span> and <span class="math">\(n_B\)</span> represent the sizes of the group A and B, respectively.
</li>
<li><span class="math">\(S^2\)</span> is an estimator of the pooled <strong>variance</strong> of the two groups. It can be calculated as follow :</li>
</ul>
<p><span class="math">\[
S^2 = \frac{\sum{(x-m_A)^2}+\sum{(x-m_B)^2}}{n_A+n_B-2}
\]</span></p>
<p>with degrees of freedom (df): <span class="math">\(df = n_A + n_B - 2\)</span>.</p>
<p>2.<strong>Welch t-statistic</strong>:</p>
<p><span class="warning">If the variances of the two groups being compared are different (<strong>heteroscedasticity</strong>), it’s possible to use the <strong>Welch t test</strong>, an adaptation of Student t-test.</span></p>
<p><strong>Welch t-statistic</strong> is calculated as follow :</p>
<p><span class="math">\[ 
t = \frac{m_A - m_B}{\sqrt{ \frac{S_A^2}{n_A} + \frac{S_B^2}{n_B} }} 
\]</span></p>
<p>where, <span class="math">\(S_A\)</span> and <span class="math">\(S_B\)</span> are the standard deviation of the the two groups A and B, respectively.</p>
<p><span class="warning">Unlike the classic Student’s t-test, <strong>Welch t-test formula</strong> involves the variance of each of the two groups (<span class="math">\(S_A^2\)</span> and <span class="math">\(S_B^2\)</span>) being compared. In other words, it does not use the pooled variance<span class="math">\(S\)</span>.</span></p>
<p>The <strong>degrees of freedom</strong> of <strong>Welch t-test</strong> is estimated as follow :</p>
<p><span class="math">\[
df = (\frac{S_A^2}{n_A}+ \frac{S_B^2}{n_B^2}) / (\frac{S_A^4}{n_A^2(n_B-1)} + \frac{S_B^4}{n_B^2(n_B-1)} )
\]</span></p>
<p><span class="success">A p-value can be computed for the corresponding absolute value of t-statistic (|t|).</span></p>
<p><span class="success">Note that, the Welch t-test is considered as the safer one. Usually, the results of the <strong>classical t-test</strong> and the <strong>Welch t-test</strong> are very similar unless both the group sizes and the standard deviations are very different.</span></p>
<p><span class="question">How to interpret the results?</span></p>
<p><span class="success">If the p-value is inferior or equal to the significance level 0.05, we can reject the null hypothesis and accept the alternative hypothesis. In other words, we can conclude that the mean values of group A and B are significantly different.</span></p>
</div>
<div id="visualize-your-data-and-compute-unpaired-two-samples-t-test-in-r" class="section level1">
<h1>Visualize your data and compute unpaired two-samples t-test in R</h1>
<div id="install-ggpubr-r-package-for-data-visualization" class="section level2">
<h2>Install ggpubr R package for data visualization</h2>
<p>You can draw R base graphs as described at this link: <a href="https://www.sthda.com/english/english/wiki/r-base-graphs">R base graphs</a>. Here, we’ll use the <a href="https://www.sthda.com/english/english/wiki/ggpubr-r-package-ggplot2-based-publication-ready-plots"><strong>ggpubr</strong> R package</a> for an easy ggplot2-based data visualization</p>
<ul>
<li>Install the latest version from GitHub as follow (recommended):</li>
</ul>
<pre class="r"><code># Install
if(!require(devtools)) install.packages("devtools")
devtools::install_github("kassambara/ggpubr")</code></pre>
<ul>
<li>Or, install from CRAN as follow:</li>
</ul>
<pre class="r"><code>install.packages("ggpubr")</code></pre>
</div>
<div id="r-function-to-compute-unpaired-two-samples-t-test" class="section level2">
<h2>R function to compute unpaired two-samples t-test</h2>
<p>To perform two-samples t-test comparing the means of two independent samples (x &amp; y), the R function <strong>t.test</strong>() can be used as follow:</p>
<pre class="r"><code>t.test(x, y, alternative = "two.sided", var.equal = FALSE)</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>x,y</strong>: numeric vectors</li>
<li><strong>alternative</strong>: the alternative hypothesis. Allowed value is one of “two.sided” (default), “greater” or “less”.</li>
<li><strong>var.equal</strong>: a logical variable indicating whether to treat the two variances as being equal. If TRUE then the pooled variance is used to estimate the variance otherwise the Welch test is used.</li>
</ul>
</div>
<p><br/></p>
</div>
<div id="import-your-data-into-r" class="section level2">
<h2>Import your data into R</h2>
<ol style="list-style-type: decimal">
<li><p><strong>Prepare your data</strong> as specified here: <a href="https://www.sthda.com/english/english/wiki/best-practices-for-preparing-your-data-set-for-r">Best practices for preparing your data set for R</a></p></li>
<li><p><strong>Save your data</strong> in an external .txt tab or .csv files</p></li>
<li><p><strong>Import your data into R</strong> as follow:</p></li>
</ol>
<pre class="r"><code># If .txt tab file, use this
my_data <- read.delim(file.choose())
# Or, if .csv file, use this
my_data <- read.csv(file.choose())</code></pre>
<p>Here, we’ll use an example data set, which contains the weight of 18 individuals (9 women and 9 men):</p>
<pre class="r"><code># Data in two numeric vectors
women_weight <- c(38.9, 61.2, 73.3, 21.8, 63.4, 64.6, 48.4, 48.8, 48.5)
men_weight <- c(67.8, 60, 63.4, 76, 89.4, 73.3, 67.3, 61.3, 62.4) 
# Create a data frame
my_data <- data.frame( 
                group = rep(c("Woman", "Man"), each = 9),
                weight = c(women_weight,  men_weight)
                )</code></pre>
<p><span class="question">We want to know, if the average women’s weight differs from the average men’s weight?</span></p>
</div>
<div id="check-your-data" class="section level2">
<h2>Check your data</h2>
<pre class="r"><code># Print all data
print(my_data)</code></pre>
<pre><code>   group weight
1  Woman   38.9
2  Woman   61.2
3  Woman   73.3
4  Woman   21.8
5  Woman   63.4
6  Woman   64.6
7  Woman   48.4
8  Woman   48.8
9  Woman   48.5
10   Man   67.8
11   Man   60.0
12   Man   63.4
13   Man   76.0
14   Man   89.4
15   Man   73.3
16   Man   67.3
17   Man   61.3
18   Man   62.4</code></pre>
<p><span class="warning">It’s possible to compute summary statistics (mean and sd) by groups. The dplyr package can be used.</span></p>
<ul>
<li>To install <strong>dplyr</strong> package, type this:</li>
</ul>
<pre class="r"><code>install.packages("dplyr")</code></pre>
<ul>
<li>Compute summary statistics by groups:</li>
</ul>
<pre class="r"><code>library(dplyr)
group_by(my_data, group) %>%
  summarise(
    count = n(),
    mean = mean(weight, na.rm = TRUE),
    sd = sd(weight, na.rm = TRUE)
  )</code></pre>
<pre><code>Source: local data frame [2 x 4]
   group count     mean        sd
  (fctr) (int)    (dbl)     (dbl)
1    Man     9 68.98889  9.375426
2  Woman     9 52.10000 15.596714</code></pre>
</div>
<div id="visualize-your-data-using-box-plots" class="section level2">
<h2>Visualize your data using box plots</h2>
<pre class="r"><code># Plot weight by group and color by group
library("ggpubr")
ggboxplot(my_data, x = "group", y = "weight", 
          color = "group", palette = c("#00AFBB", "#E7B800"),
        ylab = "Weight", xlab = "Groups")</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/unpaired-two-samples-t-test-box-plot-t-test-1.png" alt="Unpaired Two-Samples Student's T-test in R" width="336" style="margin-bottom:10px;" />
<p class="caption">
Unpaired Two-Samples Student’s T-test in R
</p>
</div>
</div>
<div id="preleminary-test-to-check-independent-t-test-assumptions" class="section level2">
<h2>Preleminary test to check independent t-test assumptions</h2>
<p><span class="question"><strong>Assumption 1</strong>: Are the two samples independents?</span></p>
<p>Yes, since the samples from men and women are not related.</p>
<p><span class="question"><strong>Assumtion 2</strong>: Are the data from each of the 2 groups follow a normal distribution?</span></p>
<p>Use Shapiro-Wilk normality test as described at: <a href="https://www.sthda.com/english/english/wiki/normality-test-in-r">Normality Test in R</a>. - Null hypothesis: the data are normally distributed - Alternative hypothesis: the data are not normally distributed</p>
<p>We’ll use the functions <strong>with</strong>() and <strong>shapiro.test</strong>() to compute Shapiro-Wilk test for each group of samples.</p>
<pre class="r"><code># Shapiro-Wilk normality test for Men's weights
with(my_data, shapiro.test(weight[group == "Man"]))# p = 0.1
# Shapiro-Wilk normality test for Women's weights
with(my_data, shapiro.test(weight[group == "Woman"])) # p = 0.6</code></pre>
<p><span class="success">From the output, the two p-values are greater than the significance level 0.05 implying that the distribution of the data are not significantly different from the normal distribution. In other words, we can assume the normality.</span></p>
<p><span class="warning">Note that, if the data are not normally distributed, it’s recommended to use the non parametric two-samples Wilcoxon rank test.</span></p>
<p><span class="question"><strong>Assumption 3</strong>. Do the two populations have the same variances?</span></p>
<p>We’ll use <strong>F-test</strong> to test for homogeneity in variances. This can be performed with the function <strong>var.test</strong>() as follow:</p>
<pre class="r"><code>res.ftest <- var.test(weight ~ group, data = my_data)
res.ftest</code></pre>
<pre><code>
    F test to compare two variances
data:  weight by group
F = 0.36134, num df = 8, denom df = 8, p-value = 0.1714
alternative hypothesis: true ratio of variances is not equal to 1
95 percent confidence interval:
 0.08150656 1.60191315
sample estimates:
ratio of variances 
         0.3613398 </code></pre>
<p><pan class = "success">The p-value of <strong>F-test</strong> is p = 0.1713596. It’s greater than the significance level alpha = 0.05. In conclusion, there is no significant difference between the variances of the two sets of data. Therefore, we can use the classic <strong>t-test</strong> witch assume equality of <strong>the two variances</strong>.</span></p>
</div>
<div id="compute-unpaired-two-samples-t-test" class="section level2">
<h2>Compute unpaired two-samples t-test</h2>
<p><span class="question">Question : Is there any significant difference between women and men weights?</span></p>
<p><strong>1) Compute independent t-test - Method 1</strong>: The data are saved in two different numeric vectors.</p>
<pre class="r"><code># Compute t-test
res <- t.test(women_weight, men_weight, var.equal = TRUE)
res</code></pre>
<pre><code>
    Two Sample t-test
data:  women_weight and men_weight
t = -2.7842, df = 16, p-value = 0.01327
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -29.748019  -4.029759
sample estimates:
mean of x mean of y 
 52.10000  68.98889 </code></pre>
<p><strong>2) Compute independent t-test - Method 2</strong>: The data are saved in a data frame.</p>
<pre class="r"><code># Compute t-test
res <- t.test(weight ~ group, data = my_data, var.equal = TRUE)
res</code></pre>
<pre><code>
    Two Sample t-test
data:  weight by group
t = 2.7842, df = 16, p-value = 0.01327
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
  4.029759 29.748019
sample estimates:
  mean in group Man mean in group Woman 
           68.98889            52.10000 </code></pre>
<p><span class="notice">As you can see, the two methods give the same results.</span></p>
<br/>
<div class="block">
<p>In the result above :</p>
<ul>
<li><strong>t</strong> is the <strong>t-test statistic</strong> value (t = 2.784),</li>
<li><strong>df</strong> is the degrees of freedom (df= 16),</li>
<li><strong>p-value</strong> is the significance level of the <strong>t-test</strong> (p-value = 0.01327).</li>
<li><strong>conf.int</strong> is the <strong>confidence interval</strong> of the mean at 95% (conf.int = [4.0298, 29.748]);</li>
<li><strong>sample estimates</strong> is he mean value of the sample (mean = 68.9888889, 52.1).</li>
</ul>
</div>
<p><br/></p>
<br/>
<div class="notice">
<p>Note that:</p>
<ul>
<li>if you want to test whether the average men’s weight is less than the average women’s weight, type this:</li>
</ul>
<pre class="r"><code>t.test(weight ~ group, data = my_data,
        var.equal = TRUE, alternative = "less")</code></pre>
<ul>
<li>Or, if you want to test whether the average men’s weight is greater than the average women’s weight, type this</li>
</ul>
<pre class="r"><code>t.test(weight ~ group, data = my_data,
        var.equal = TRUE, alternative = "greater")</code></pre>
</div>
<p><br/></p>
</div>
<div id="interpretation-of-the-result" class="section level2">
<h2>Interpretation of the result</h2>
<p><span class="success">The <strong>p-value</strong> of the test is 0.01327, which is less than the significance level alpha = 0.05. We can conclude that men’s average weight is significantly different from women’s average weight with a <strong>p-value</strong> = 0.01327.</span></p>
</div>
<div id="access-to-the-values-returned-by-t.test-function" class="section level2">
<h2>Access to the values returned by t.test() function</h2>
<p>The result of <strong>t.test()</strong> function is a list containing the following components:</p>
<br/>
<div class="block">
<ul>
<li><strong>statistic</strong>: the value of the <strong>t test statistics</strong></li>
<li><strong>parameter</strong>: the <strong>degrees of freedom</strong> for the <strong>t test statistics</strong></li>
<li><strong>p.value</strong>: the <strong>p-value</strong> for the test</li>
<li><strong>conf.int</strong>: a <strong>confidence interval</strong> for the mean appropriate to the specified <strong>alternative hypothesis</strong>.</li>
<li><strong>estimate</strong>: the means of the two groups being compared (in the case of <strong>independent t test</strong>) or difference in means (in the case of <strong>paired t test</strong>).</li>
</ul>
</div>
<p><br/></p>
<p>The format of the <strong>R</strong> code to use for getting these values is as follow:</p>
<pre class="r"><code># printing the p-value
res$p.value</code></pre>
<pre><code>[1] 0.0132656</code></pre>
<pre class="r"><code># printing the mean
res$estimate</code></pre>
<pre><code>  mean in group Man mean in group Woman 
           68.98889            52.10000 </code></pre>
<pre class="r"><code># printing the confidence interval
res$conf.int</code></pre>
<pre><code>[1]  4.029759 29.748019
attr(,"conf.level")
[1] 0.95</code></pre>
</div>
</div>
<div id="online-unpaired-two-samples-t-test-calculator" class="section level1">
<h1>Online unpaired two-samples t-test calculator</h1>
<p>You can perform unpaired <strong>two-samples t-test</strong>, <strong>online</strong>, without any installation by clicking the following link:</p>
<br/>
<div class="block">
<i class="fa - fa-cogs fa-4x valign_middle"></i> <a href="https://www.sthda.com/english/english/rsthda/unpaired-t-test.php">Online two-samples t-test calculator</a>
</div>
<p><br/></p>
</div>
<div id="see-also" class="section level1">
<h1>See also</h1>
<ul>
<li>Compare one-sample mean to a standard known mean
<ul>
<li><a href="https://www.sthda.com/english/english/wiki/one-sample-t-test-in-r">One-Sample T-test (parametric)</a></li>
<li><a href="https://www.sthda.com/english/english/wiki/one-sample-wilcoxon-signed-rank-test-in-r">One-Sample Wilcoxon Test (non-parametric)</a></li>
</ul></li>
<li>Compare the means of two independent groups
<ul>
<li><a href="https://www.sthda.com/english/english/wiki/unpaired-two-samples-wilcoxon-test-in-r">Unpaired Two-Samples Wilcoxon Test (non-parametric)</a></li>
</ul></li>
</ul>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.2.4). </span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
  (function () {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src  = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
    document.getElementsByTagName("head")[0].appendChild(script);
  })();
</script>
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 08:29:02 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[One-Sample Wilcoxon Signed Rank Test in R]]></title>
			<link>https://www.sthda.com/english/wiki/one-sample-wilcoxon-signed-rank-test-in-r</link>
			<guid>https://www.sthda.com/english/wiki/one-sample-wilcoxon-signed-rank-test-in-r</guid>
			<description><![CDATA[<!-- START HTML -->

            
  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#whats-one-sample-wilcoxon-signed-rank-test">What’s one-sample Wilcoxon signed rank test?</a></li>
<li><a href="#research-questions-and-statistical-hypotheses">Research questions and statistical hypotheses</a></li>
<li><a href="#visualize-your-data-and-compute-one-sample-wilcoxon-test-in-r">Visualize your data and compute one-sample Wilcoxon test in R</a><ul>
<li><a href="#install-ggpubr-r-package-for-data-visualization">Install ggpubr R package for data visualization</a></li>
<li><a href="#r-function-to-compute-one-sample-wilcoxon-test">R function to compute one-sample Wilcoxon test</a></li>
<li><a href="#import-your-data-into-r">Import your data into R</a></li>
<li><a href="#check-your-data">Check your data</a></li>
<li><a href="#visualize-your-data-using-box-plots">Visualize your data using box plots</a></li>
<li><a href="#compute-one-sample-wilcoxon-test">Compute one-sample Wilcoxon test</a></li>
</ul></li>
<li><a href="#see-also">See also</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<div id="whats-one-sample-wilcoxon-signed-rank-test" class="section level1">
<h1>What’s one-sample Wilcoxon signed rank test?</h1>
<br/>
<div class="block">
The <strong>one-sample Wilcoxon signed rank test</strong> is a non-parametric alternative to <strong>one-sample t-test</strong> when the data cannot be assumed to be normally distributed. It’s used to determine whether the median of the sample is equal to a known standard value (i.e. theoretical value).
</div>
<p><br/></p>
<p><span class="error"> Note that, the data should be distributed symmetrically around the median. In other words, there should be roughly the same number of values above and below the median. </span></p>
<p><br/> <img src="https://www.sthda.com/english/sthda/RDoc/images/one-sample-wilcoxon-test.png" alt="One Sample Wilcoxon test" /> <br/></p>
</div>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/pqs3" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/r-statistics-for-comparing-means.png" /><br/>
     Practical Statistics in R for Comparing Groups: Numerical Variables
      </a>
</div>
<div class="spacer"></div>

<div id="research-questions-and-statistical-hypotheses" class="section level1">
<h1>Research questions and statistical hypotheses</h1>
<p>Typical research questions are:</p>
<br/>
<div class="question">
<ol style="list-style-type: decimal">
<li>whether the median (<span class="math">\(m\)</span>) of the sample <em>is equal</em> to the theoretical value (<span class="math">\(m_0\)</span>)?</li>
<li>whether the median (<span class="math">\(m\)</span>) of the sample <em>is less than</em> to the theoretical value (<span class="math">\(m_0\)</span>)?</li>
<li>whether the median (<span class="math">\(m\)</span>) of the sample <em>is greater than</em> to the theoretical value(<span class="math">\(m_0\)</span>)?</li>
</ol>
</div>
<p><br/></p>
<p>In statistics, we can define the corresponding <em>null hypothesis</em> (<span class="math">\(H_0\)</span>) as follow:</p>
<ol style="list-style-type: decimal">
<li><span class="math">\(H_0: m = m_0\)</span></li>
<li><span class="math">\(H_0: m \leq m_0\)</span></li>
<li><span class="math">\(H_0: m \geq m_0\)</span></li>
</ol>
<p>The corresponding <em>alternative hypotheses</em> (<span class="math">\(H_a\)</span>) are as follow:</p>
<ol style="list-style-type: decimal">
<li><span class="math">\(H_a: m \ne m_0\)</span> (different)</li>
<li><span class="math">\(H_a: m > m_0\)</span> (greater)</li>
<li><span class="math">\(H_a: m < m_0\)</span> (less)</li>
</ol>
<div class="notice">
<p>Note that:</p>
<ul>
<li>Hypotheses 1) are called <strong>two-tailed tests</strong></li>
<li>Hypotheses 2) and 3) are called <strong>one-tailed tests</strong></li>
</ul>
</div>
</div>
<div id="visualize-your-data-and-compute-one-sample-wilcoxon-test-in-r" class="section level1">
<h1>Visualize your data and compute one-sample Wilcoxon test in R</h1>
<div id="install-ggpubr-r-package-for-data-visualization" class="section level2">
<h2>Install ggpubr R package for data visualization</h2>
<p>You can draw R base graphs as described at this link: <a href="https://www.sthda.com/english/english/wiki/r-base-graphs">R base graphs</a>. Here, we’ll use the <a href="https://www.sthda.com/english/english/wiki/ggpubr-r-package-ggplot2-based-publication-ready-plots"><strong>ggpubr</strong> R package</a> for an easy ggplot2-based data visualization</p>
<ul>
<li>Install the latest version from GitHub as follow (recommended):</li>
</ul>
<pre class="r"><code># Install
if(!require(devtools)) install.packages("devtools")
devtools::install_github("kassambara/ggpubr")</code></pre>
<ul>
<li>Or, install from CRAN as follow:</li>
</ul>
<pre class="r"><code>install.packages("ggpubr")</code></pre>
</div>
<div id="r-function-to-compute-one-sample-wilcoxon-test" class="section level2">
<h2>R function to compute one-sample Wilcoxon test</h2>
<p>To perform one-sample Wilcoxon-test, the R function <strong>wilcox.test</strong>() can be used as follow:</p>
<pre class="r"><code>wilcox.test(x, mu = 0, alternative = "two.sided")</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>x</strong>: a numeric vector containing your data values</li>
<li><strong>mu</strong>: the theoretical mean/median value. Default is 0 but you can change it.</li>
<li><strong>alternative</strong>: the alternative hypothesis. Allowed value is one of “two.sided” (default), “greater” or “less”.</li>
</ul>
</div>
<p><br/></p>
</div>
<div id="import-your-data-into-r" class="section level2">
<h2>Import your data into R</h2>
<ol style="list-style-type: decimal">
<li><p><strong>Prepare your data</strong> as specified here: <a href="https://www.sthda.com/english/english/wiki/best-practices-for-preparing-your-data-set-for-r">Best practices for preparing your data set for R</a></p></li>
<li><p><strong>Save your data</strong> in an external .txt tab or .csv files</p></li>
<li><p><strong>Import your data into R</strong> as follow:</p></li>
</ol>
<pre class="r"><code># If .txt tab file, use this
my_data <- read.delim(file.choose())
# Or, if .csv file, use this
my_data <- read.csv(file.choose())</code></pre>
<p><span class="notice">Here, we’ll use an example data set containing the weight of 10 mice.</span></p>
<p><span class="question">We want to know, if the median weight of the mice differs from 25g?</span></p>
<pre class="r"><code>set.seed(1234)
my_data <- data.frame(
  name = paste0(rep("M_", 10), 1:10),
  weight = round(rnorm(10, 20, 2), 1)
)</code></pre>
</div>
<div id="check-your-data" class="section level2">
<h2>Check your data</h2>
<pre class="r"><code># Print the first 10 rows of the data
head(my_data, 10)</code></pre>
<pre><code>   name weight
1   M_1   17.6
2   M_2   20.6
3   M_3   22.2
4   M_4   15.3
5   M_5   20.9
6   M_6   21.0
7   M_7   18.9
8   M_8   18.9
9   M_9   18.9
10 M_10   18.2</code></pre>
<pre class="r"><code># Statistical summaries of weight
summary(my_data$weight)</code></pre>
<pre><code>   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  15.30   18.38   18.90   19.25   20.82   22.20 </code></pre>
<ul>
<li><strong>Min.</strong>: the minimum value</li>
<li><strong>1st Qu.</strong>: The first quartile. 25% of values are lower than this.</li>
<li><strong>Median</strong>: the median value. Half the values are lower; half are higher.</li>
<li><strong>3rd Qu.</strong>: the third quartile. 75% of values are higher than this.</li>
<li><strong>Max.</strong>: the maximum value</li>
</ul>
</div>
<div id="visualize-your-data-using-box-plots" class="section level2">
<h2>Visualize your data using box plots</h2>
<pre class="r"><code>library(ggpubr)
ggboxplot(my_data$weight, 
          ylab = "Weight (g)", xlab = FALSE,
          ggtheme = theme_minimal())</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/one-sample-wilcoxon-signed-rank-test-box-plot-1.png" alt="One-Sample Wilcoxon Signed Rank Test in R" width="288" style="margin-bottom:10px;" />
<p class="caption">
One-Sample Wilcoxon Signed Rank Test in R
</p>
</div>
</div>
<div id="compute-one-sample-wilcoxon-test" class="section level2">
<h2>Compute one-sample Wilcoxon test</h2>
<p><span class="question">We want to know, if the average weight of the mice differs from 25g (two-tailed test)?</span></p>
<pre class="r"><code># One-sample wilcoxon test
res <- wilcox.test(my_data$weight, mu = 25)
# Printing the results
res </code></pre>
<pre><code>
    Wilcoxon signed rank test with continuity correction
data:  my_data$weight
V = 0, p-value = 0.005793
alternative hypothesis: true location is not equal to 25</code></pre>
<pre class="r"><code># print only the p-value
res$p.value</code></pre>
<pre><code>[1] 0.005793045</code></pre>
<p><span class="success"> The <strong>p-value</strong> of the test is 0.005793, which is less than the significance level alpha = 0.05. We can reject the null hypothesis and conclude that the average weight of the mice is significantly different from 25g with a <strong>p-value</strong> = 0.005793. </span></p>
<br/>
<div class="notice">
<p>Note that:</p>
<ul>
<li>if you want to test whether the median weight of mice is less than 25g (one-tailed test), type this:</li>
</ul>
<pre class="r"><code>wilcox.test(my_data$weight, mu = 25,
              alternative = "less")</code></pre>
<ul>
<li>Or, if you want to test whether the median weight of mice is greater than 25g (one-tailed test), type this:</li>
</ul>
<pre class="r"><code>wilcox.test(my_data$weight, mu = 25,
              alternative = "greater")</code></pre>
</div>
<p><br/></p>
</div>
</div>
<div id="see-also" class="section level1">
<h1>See also</h1>
<p><a href="https://www.sthda.com/english/english/wiki/one-sample-t-test-in-r">One-sample t-test (parametric)</a></p>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.2.4). </span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
  (function () {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src  = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
    document.getElementsByTagName("head")[0].appendChild(script);
  })();
</script>
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 08:28:10 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[One-Sample T-test in R]]></title>
			<link>https://www.sthda.com/english/wiki/one-sample-t-test-in-r</link>
			<guid>https://www.sthda.com/english/wiki/one-sample-t-test-in-r</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#what-is-one-sample-t-test">What is one-sample t-test?</a></li>
<li><a href="#research-questions-and-statistical-hypotheses">Research questions and statistical hypotheses</a></li>
<li><a href="#formula-of-one-sample-t-test">Formula of one-sample t-test</a></li>
<li><a href="#visualize-your-data-and-compute-one-sample-t-test-in-r">Visualize your data and compute one-sample t-test in R</a><ul>
<li><a href="#install-ggpubr-r-package-for-data-visualization">Install ggpubr R package for data visualization</a></li>
<li><a href="#r-function-to-compute-one-sample-t-test">R function to compute one-sample t-test</a></li>
<li><a href="#import-your-data-into-r">Import your data into R</a></li>
<li><a href="#check-your-data">Check your data</a></li>
<li><a href="#visualize-your-data-using-box-plots">Visualize your data using box plots</a></li>
<li><a href="#preleminary-test-to-check-one-sample-t-test-assumptions">Preleminary test to check one-sample t-test assumptions</a></li>
<li><a href="#compute-one-sample-t-test">Compute one-sample t-test</a></li>
<li><a href="#interpretation-of-the-result">Interpretation of the result</a></li>
<li><a href="#access-to-the-values-returned-by-t.test-function">Access to the values returned by t.test() function</a></li>
</ul></li>
<li><a href="#online-one-sample-t-test-calculator">Online one-sample t-test calculator</a></li>
<li><a href="#see-also">See also</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<div id="what-is-one-sample-t-test" class="section level1">
<h1>What is one-sample t-test?</h1>
<br/>
<div class="block">
<strong>one-sample t-test</strong> is used to compare the <strong>mean</strong> of one sample to a known standard (or <strong>theoretical/hypothetical</strong>) <strong>mean</strong> (<span class="math">\(\mu\)</span>).
</div>
<p><br/></p>
<p>Generally, the theoretical mean comes from:</p>
<ul>
<li>a previous experiment. For example, compare whether the mean weight of mice differs from 200 mg, a value determined in a previous study.</li>
<li>or from an experiment where you have control and treatment conditions. If you express your data as “percent of control”, you can test whether the average value of treatment condition differs significantly from 100.</li>
</ul>
<p><span class="error">Note that, one-sample t-test can be used only, when the data are <a href="https://www.sthda.com/english/english/wiki/normality-test-in-r">normally distributed</a> . This can be checked using <a href="https://www.sthda.com/english/english/wiki/normality-test-in-r"><strong>Shapiro-Wilk test</strong></a> .</span></p>
<p><br/> <img src="https://www.sthda.com/english/sthda/RDoc/images/one-sample-t-test.png" alt="One Sample t-test" /> <br/></p>
</div>

<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/pqs3" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/r-statistics-for-comparing-means.png" /><br/>
     Practical Statistics in R for Comparing Groups: Numerical Variables
      </a>
</div>
<div class="spacer"></div>

<div id="research-questions-and-statistical-hypotheses" class="section level1">
<h1>Research questions and statistical hypotheses</h1>
<p>Typical research questions are:</p>
<br/>
<div class="question">
<ol style="list-style-type: decimal">
<li>whether the mean (<span class="math">\(m\)</span>) of the sample <em>is equal</em> to the theoretical mean (<span class="math">\(\mu\)</span>)?</li>
<li>whether the mean (<span class="math">\(m\)</span>) of the sample <em>is less than</em> the theoretical mean (<span class="math">\(\mu\)</span>)?</li>
<li>whether the mean (<span class="math">\(m\)</span>) of the sample <em>is greater than</em> the theoretical mean (<span class="math">\(\mu\)</span>)?</li>
</ol>
</div>
<p><br/></p>
<p>In statistics, we can define the corresponding <em>null hypothesis</em> (<span class="math">\(H_0\)</span>) as follow:</p>
<ol style="list-style-type: decimal">
<li><span class="math">\(H_0: m = \mu\)</span></li>
<li><span class="math">\(H_0: m \leq \mu\)</span></li>
<li><span class="math">\(H_0: m \geq \mu\)</span></li>
</ol>
<p>The corresponding <em>alternative hypotheses</em> (<span class="math">\(H_a\)</span>) are as follow:</p>
<ol style="list-style-type: decimal">
<li><span class="math">\(H_a: m \ne \mu\)</span> (different)</li>
<li><span class="math">\(H_a: m > \mu\)</span> (greater)</li>
<li><span class="math">\(H_a: m < \mu\)</span> (less)</li>
</ol>
<div class="notice">
<p>Note that:</p>
<ul>
<li>Hypotheses 1) are called <strong>two-tailed tests</strong></li>
<li>Hypotheses 2) and 3) are called <strong>one-tailed tests</strong></li>
</ul>
</div>
</div>
<div id="formula-of-one-sample-t-test" class="section level1">
<h1>Formula of one-sample t-test</h1>
<p>The t-statistic can be calculated as follow:</p>
<p><span class="math">\[
t = \frac{m-\mu}{s/\sqrt{n}}
\]</span></p>
<p>where,</p>
<ul>
<li><strong>m</strong> is the sample <strong>mean</strong></li>
<li><strong>n</strong> is the sample <strong>size</strong></li>
<li><strong>s</strong> is the sample <strong>standard deviation</strong> with <span class="math">\(n-1\)</span> <strong>degrees of freedom</strong></li>
<li><span class="math">\(\mu\)</span> is the <strong>theoretical value</strong></li>
</ul>
<p>We can compute the p-value corresponding to the absolute value of the <strong>t-test statistics</strong> (|t|) for the <strong>degrees of freedom</strong> (df): <span class="math">\(df = n - 1\)</span>.</p>
<p><span class="question">How to interpret the results?</span></p>
<p><span class="success">If the p-value is inferior or equal to the significance level 0.05, we can reject the null hypothesis and accept the alternative hypothesis. In other words, we conclude that the sample mean is significantly different from the theoretical mean.</span></p>
</div>
<div id="visualize-your-data-and-compute-one-sample-t-test-in-r" class="section level1">
<h1>Visualize your data and compute one-sample t-test in R</h1>
<div id="install-ggpubr-r-package-for-data-visualization" class="section level2">
<h2>Install ggpubr R package for data visualization</h2>
<p>You can draw R base graps as described at this link: <a href="https://www.sthda.com/english/english/wiki/r-base-graphs">R base graphs</a>. Here, we’ll use the <a href="https://www.sthda.com/english/english/wiki/ggpubr-r-package-ggplot2-based-publication-ready-plots"><strong>ggpubr</strong> R package</a> for an easy ggplot2-based data visualization</p>
<ul>
<li>Install the latest version from GitHub as follow (recommended):</li>
</ul>
<pre class="r"><code># Install
if(!require(devtools)) install.packages("devtools")
devtools::install_github("kassambara/ggpubr")</code></pre>
<ul>
<li>Or, install from CRAN as follow:</li>
</ul>
<pre class="r"><code>install.packages("ggpubr")</code></pre>
</div>
<div id="r-function-to-compute-one-sample-t-test" class="section level2">
<h2>R function to compute one-sample t-test</h2>
<p>To perform one-sample t-test, the R function <strong>t.test</strong>() can be used as follow:</p>
<pre class="r"><code>t.test(x, mu = 0, alternative = "two.sided")</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>x</strong>: a numeric vector containing your data values</li>
<li><strong>mu</strong>: the theoretical mean. Default is 0 but you can change it.</li>
<li><strong>alternative</strong>: the alternative hypothesis. Allowed value is one of “two.sided” (default), “greater” or “less”.</li>
</ul>
</div>
<p><br/></p>
</div>
<div id="import-your-data-into-r" class="section level2">
<h2>Import your data into R</h2>
<ol style="list-style-type: decimal">
<li><p><strong>Prepare your data</strong> as specified here: <a href="https://www.sthda.com/english/english/wiki/best-practices-for-preparing-your-data-set-for-r">Best practices for preparing your data set for R</a></p></li>
<li><p><strong>Save your data</strong> in an external .txt tab or .csv files</p></li>
<li><p><strong>Import your data into R</strong> as follow:</p></li>
</ol>
<pre class="r"><code># If .txt tab file, use this
my_data <- read.delim(file.choose())
# Or, if .csv file, use this
my_data <- read.csv(file.choose())</code></pre>
<p><span class="notice">Here, we’ll use an example data set containing the weight of 10 mice.</span></p>
<p><span class="question">We want to know, if the average weight of the mice differs from 25g?</span></p>
<pre class="r"><code>set.seed(1234)
my_data <- data.frame(
  name = paste0(rep("M_", 10), 1:10),
  weight = round(rnorm(10, 20, 2), 1)
)</code></pre>
</div>
<div id="check-your-data" class="section level2">
<h2>Check your data</h2>
<pre class="r"><code># Print the first 10 rows of the data
head(my_data, 10)</code></pre>
<pre><code>   name weight
1   M_1   17.6
2   M_2   20.6
3   M_3   22.2
4   M_4   15.3
5   M_5   20.9
6   M_6   21.0
7   M_7   18.9
8   M_8   18.9
9   M_9   18.9
10 M_10   18.2</code></pre>
<pre class="r"><code># Statistical summaries of weight
summary(my_data$weight)</code></pre>
<pre><code>   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  15.30   18.38   18.90   19.25   20.82   22.20 </code></pre>
<ul>
<li><strong>Min.</strong>: the minimum value</li>
<li><strong>1st Qu.</strong>: The first quartile. 25% of values are lower than this.</li>
<li><strong>Median</strong>: the median value. Half the values are lower; half are higher.</li>
<li><strong>3rd Qu.</strong>: the third quartile. 75% of values are higher than this.</li>
<li><strong>Max.</strong>: the maximum value</li>
</ul>
</div>
<div id="visualize-your-data-using-box-plots" class="section level2">
<h2>Visualize your data using box plots</h2>
<pre class="r"><code>library(ggpubr)
ggboxplot(my_data$weight, 
          ylab = "Weight (g)", xlab = FALSE,
          ggtheme = theme_minimal())</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/one-sample-t-test-box-plot-1.png" alt="One-Sample Student's T-test in R" width="288" style="margin-bottom:10px;" />
<p class="caption">
One-Sample Student’s T-test in R
</p>
</div>
</div>
<div id="preleminary-test-to-check-one-sample-t-test-assumptions" class="section level2">
<h2>Preleminary test to check one-sample t-test assumptions</h2>
<ol style="list-style-type: decimal">
<li><strong>Is this a large sample</strong>? - No, because n < 30.</li>
<li>Since the sample size is not large enough (less than 30, central limit theorem), we need to <strong>check whether the data follow a normal distribution</strong>.</li>
</ol>
<p><span class="question">How to check the normality?</span></p>
<p>Read this article: <a href="https://www.sthda.com/english/english/wiki/normality-test-in-r">Normality Test in R</a>.</p>
<p>Briefly, it’s possible to use the <strong>Shapiro-Wilk normality test</strong> and to look at the <strong>normality plot</strong>.</p>
<ol style="list-style-type: decimal">
<li><strong>Shapiro-Wilk test</strong>:
<ul>
<li>Null hypothesis: the data are normally distributed</li>
<li>Alternative hypothesis: the data are not normally distributed</li>
</ul></li>
</ol>
<pre class="r"><code>shapiro.test(my_data$weight) # => p-value = 0.6993</code></pre>
<p><span class="success">From the output, the p-value is greater than the significance level 0.05 implying that the distribution of the data are not significantly different from normal distribtion. In other words, we can assume the normality.</span></p>
<ul>
<li><strong>Visual inspection</strong> of the data normality using <strong>Q-Q plots</strong> (quantile-quantile plots). Q-Q plot draws the correlation between a given sample and the normal distribution.</li>
</ul>
<pre class="r"><code>library("ggpubr")
ggqqplot(my_data$weight, ylab = "Men's weight",
         ggtheme = theme_minimal())</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/one-sample-t-test-qqplot-1.png" alt="One-Sample Student's T-test in R" width="288" style="margin-bottom:10px;" />
<p class="caption">
One-Sample Student’s T-test in R
</p>
</div>
<p><span class="success">From the normality plots, we conclude that the data may come from normal distributions.</span></p>
<p><span class="warning">Note that, if the data are not normally distributed, it’s recommended to use the non parametric one-sample Wilcoxon rank test.</span></p>
</div>
<div id="compute-one-sample-t-test" class="section level2">
<h2>Compute one-sample t-test</h2>
<p><span class="question">We want to know, if the average weight of the mice differs from 25g (two-tailed test)?</span></p>
<pre class="r"><code># One-sample t-test
res <- t.test(my_data$weight, mu = 25)
# Printing the results
res </code></pre>
<pre><code>
    One Sample t-test
data:  my_data$weight
t = -9.0783, df = 9, p-value = 7.953e-06
alternative hypothesis: true mean is not equal to 25
95 percent confidence interval:
 17.8172 20.6828
sample estimates:
mean of x 
    19.25 </code></pre>
<br/>
<div class="block">
<p>In the result above :</p>
<ul>
<li><strong>t</strong> is the <strong>t-test statistic</strong> value (t = -9.078),</li>
<li><strong>df</strong> is the degrees of freedom (df= 9),</li>
<li><strong>p-value</strong> is the significance level of the <strong>t-test</strong> (p-value = 7.95310^{-6}).</li>
<li><strong>conf.int</strong> is the <strong>confidence interval</strong> of the mean at 95% (conf.int = [17.8172, 20.6828]);</li>
<li><strong>sample estimates</strong> is he mean value of the sample (mean = 19.25).</li>
</ul>
</div>
<p><br/></p>
<br/>
<div class="notice">
<p>Note that:</p>
<ul>
<li>if you want to test whether the mean weight of mice is less than 25g (one-tailed test), type this:</li>
</ul>
<pre class="r"><code>t.test(my_data$weight, mu = 25,
              alternative = "less")</code></pre>
<ul>
<li>Or, if you want to test whether the mean weight of mice is greater than 25g (one-tailed test), type this:</li>
</ul>
<pre class="r"><code>t.test(my_data$weight, mu = 25,
              alternative = "greater")</code></pre>
</div>
<p><br/></p>
</div>
<div id="interpretation-of-the-result" class="section level2">
<h2>Interpretation of the result</h2>
<p><span class="success"> The <strong>p-value</strong> of the test is 7.95310^{-6}, which is less than the significance level alpha = 0.05. We can conclude that the mean weight of the mice is significantly different from 25g with a <strong>p-value</strong> = 7.95310^{-6}. </span></p>
</div>
<div id="access-to-the-values-returned-by-t.test-function" class="section level2">
<h2>Access to the values returned by t.test() function</h2>
<p>The result of <strong>t.test()</strong> function is a list containing the following components:</p>
<br/>
<div class="block">
<ul>
<li><strong>statistic</strong>: the value of the <strong>t test statistics</strong></li>
<li><strong>parameter</strong>: the <strong>degrees of freedom</strong> for the <strong>t test statistics</strong></li>
<li><strong>p.value</strong>: the <strong>p-value</strong> for the test</li>
<li><strong>conf.int</strong>: a <strong>confidence interval</strong> for the mean appropriate to the specified <strong>alternative hypothesis</strong>.</li>
<li><strong>estimate</strong>: the means of the two groups being compared (in the case of <strong>independent t test</strong>) or difference in means (in the case of <strong>paired t test</strong>).</li>
</ul>
</div>
<p><br/></p>
<p>The format of the <strong>R</strong> code to use for getting these values is as follow:</p>
<pre class="r"><code># printing the p-value
res$p.value</code></pre>
<pre><code>[1] 7.953383e-06</code></pre>
<pre class="r"><code># printing the mean
res$estimate</code></pre>
<pre><code>mean of x 
    19.25 </code></pre>
<pre class="r"><code># printing the confidence interval
res$conf.int</code></pre>
<pre><code>[1] 17.8172 20.6828
attr(,"conf.level")
[1] 0.95</code></pre>
</div>
</div>
<div id="online-one-sample-t-test-calculator" class="section level1">
<h1>Online one-sample t-test calculator</h1>
<p>You can perform <strong>one-sample t-test</strong>, <strong>online</strong>, without any installation by clicking the following link:</p>
<br/>
<div class="block">
<i class="fa - fa-cogs fa-4x valign_middle"></i> <a href="https://www.sthda.com/english/english/rsthda/one-sample-t-test.php">Online one-sample t-test calculator</a>
</div>
<p><br/></p>
</div>
<div id="see-also" class="section level1">
<h1>See also</h1>
<p><a href="https://www.sthda.com/english/english/wiki/one-sample-wilcoxon-signed-rank-test-in-r">One-sample wilcoxon test (non-parametric)</a></p>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.2.4). </span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
  (function () {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src  = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
    document.getElementsByTagName("head")[0].appendChild(script);
  })();
</script>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 08:26:23 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Paired Samples T-test in R]]></title>
			<link>https://www.sthda.com/english/wiki/paired-samples-t-test-in-r</link>
			<guid>https://www.sthda.com/english/wiki/paired-samples-t-test-in-r</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#what-is-paired-samples-t-test">What is paired samples t-test?</a></li>
<li><a href="#research-questions-and-statistical-hypotheses">Research questions and statistical hypotheses</a></li>
<li><a href="#formula-of-paired-samples-t-test">Formula of paired samples t-test</a></li>
<li><a href="#visualize-your-data-and-compute-paired-t-test-in-r">Visualize your data and compute paired t-test in R</a><ul>
<li><a href="#r-function-to-compute-paired-t-test">R function to compute paired t-test</a></li>
<li><a href="#import-your-data-into-r">Import your data into R</a></li>
<li><a href="#check-your-data">Check your data</a></li>
<li><a href="#visualize-your-data-using-box-plots">Visualize your data using box plots</a></li>
<li><a href="#preleminary-test-to-check-paired-t-test-assumptions">Preleminary test to check paired t-test assumptions</a></li>
<li><a href="#compute-paired-samples-t-test">Compute paired samples t-test</a></li>
<li><a href="#interpretation-of-the-result">Interpretation of the result</a></li>
<li><a href="#access-to-the-values-returned-by-t.test-function">Access to the values returned by t.test() function</a></li>
</ul></li>
<li><a href="#online-paired-t-test-calculator">Online paired t-test calculator</a></li>
<li><a href="#see-also">See also</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<div id="what-is-paired-samples-t-test" class="section level1">
<h1>What is paired samples t-test?</h1>
<br/>
<div class="block">
The <strong>paired samples t-test</strong> is used to compare the means between two related groups of samples. In this case, you have two values (i.e., pair of values) for the same samples. This article describes how to compute <strong>paired samples t-test</strong> using <strong>R software</strong>.
</div>
<p><br/></p>
<p>As an example of data, 20 mice received a treatment X during 3 months. We want to know whether the treatment X has an impact on the weight of the mice.</p>
<p>To answer to this question, the weight of the 20 mice has been measured before and after the treatment. This gives us 20 sets of values before treatment and 20 sets of values after treatment from measuring twice the weight of the <strong>same mice</strong>.</p>
<p>In such situations, <strong>paired t-test</strong> can be used to compare the mean weights before and after treatment.</p>
<p>Paired t-test analysis is performed as follow:</p>
<ol style="list-style-type: decimal">
<li>Calculate the difference (<span class="math">\(d\)</span>) between each pair of value</li>
<li>Compute the mean (<span class="math">\(m\)</span>) and the standard deviation (<span class="math">\(s\)</span>) of <span class="math">\(d\)</span></li>
<li>Compare the average difference to 0. If there is any significant difference between the two pairs of samples, then the mean of d (<span class="math">\(m\)</span>) is expected to be far from 0.</li>
</ol>
<p><span class="error"> Paired t-test can be used only when the difference <span class="math">\(d\)</span> is normally distributed. This can be checked using <a href="https://www.sthda.com/english/english/wiki/normality-test-in-r"><strong>Shapiro-Wilk test</strong></a>. </span></p>
<p><br/> <img src="https://www.sthda.com/english/sthda/RDoc/images/paired-samples-t-test.png" alt="Paired samples t test" /> <br/></p>
</div>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/pqs3" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/r-statistics-for-comparing-means.png" /><br/>
     Practical Statistics in R for Comparing Groups: Numerical Variables
      </a>
</div>
<div class="spacer"></div>
<div id="research-questions-and-statistical-hypotheses" class="section level1">
<h1>Research questions and statistical hypotheses</h1>
<p>Typical research questions are:</p>
<br/>
<div class="question">
<ol style="list-style-type: decimal">
<li>whether the mean difference (<span class="math">\(m\)</span>) <em>is equal</em> to 0?</li>
<li>whether the mean difference (<span class="math">\(m\)</span>) <em>is less than</em> 0?</li>
<li>whether the mean difference (<span class="math">\(m\)</span>) <em>is greather than</em> 0?</li>
</ol>
</div>
<p><br/></p>
<p>In statistics, we can define the corresponding <em>null hypothesis</em> (<span class="math">\(H_0\)</span>) as follow:</p>
<ol style="list-style-type: decimal">
<li><span class="math">\(H_0: m = 0\)</span></li>
<li><span class="math">\(H_0: m \leq 0\)</span></li>
<li><span class="math">\(H_0: m \geq 0\)</span></li>
</ol>
<p>The corresponding <em>alternative hypotheses</em> (<span class="math">\(H_a\)</span>) are as follow:</p>
<ol style="list-style-type: decimal">
<li><span class="math">\(H_a: m \ne 0\)</span> (different)</li>
<li><span class="math">\(H_a: m > 0\)</span> (greater)</li>
<li><span class="math">\(H_a: m < 0\)</span> (less)</li>
</ol>
<div class="notice">
<p>Note that:</p>
<ul>
<li>Hypotheses 1) are called <strong>two-tailed tests</strong></li>
<li>Hypotheses 2) and 3) are called <strong>one-tailed tests</strong></li>
</ul>
</div>
</div>
<div id="formula-of-paired-samples-t-test" class="section level1">
<h1>Formula of paired samples t-test</h1>
<p><strong>t-test statistisc value</strong> can be calculated using the following formula:</p>
<p><span class="math">\[
t = \frac{m}{s/\sqrt{n}}
\]</span></p>
<p>where,</p>
<ul>
<li><strong>m</strong> is the mean differences</li>
<li><strong>n</strong> is the sample size (i.e., size of d).</li>
<li><strong>s</strong> is the standard deviation of d</li>
</ul>
<p>We can compute the p-value corresponding to the absolute value of the <strong>t-test statistics</strong> (|t|) for the <strong>degrees of freedom</strong> (df): <span class="math">\(df = n - 1\)</span>.</p>
<p><span class="success">If the p-value is inferior or equal to 0.05, we can conclude that the difference between the two paired samples are significantly different.</span></p>
</div>
<div id="visualize-your-data-and-compute-paired-t-test-in-r" class="section level1">
<h1>Visualize your data and compute paired t-test in R</h1>
<div id="r-function-to-compute-paired-t-test" class="section level2">
<h2>R function to compute paired t-test</h2>
<p>To perform paired samples t-test comparing the means of two paired samples (x &amp; y), the R function <strong>t.test</strong>() can be used as follow:</p>
<pre class="r"><code>t.test(x, y, paired = TRUE, alternative = "two.sided")</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>x,y</strong>: numeric vectors</li>
<li><strong>paired</strong>: a logical value specifying that we want to compute a paired t-test</li>
<li><strong>alternative</strong>: the alternative hypothesis. Allowed value is one of “two.sided” (default), “greater” or “less”.</li>
</ul>
</div>
<p><br/></p>
</div>
<div id="import-your-data-into-r" class="section level2">
<h2>Import your data into R</h2>
<ol style="list-style-type: decimal">
<li><p><strong>Prepare your data</strong> as specified here: <a href="https://www.sthda.com/english/english/wiki/best-practices-for-preparing-your-data-set-for-r">Best practices for preparing your data set for R</a></p></li>
<li><p><strong>Save your data</strong> in an external .txt tab or .csv files</p></li>
<li><p><strong>Import your data into R</strong> as follow:</p></li>
</ol>
<pre class="r"><code># If .txt tab file, use this
my_data <- read.delim(file.choose())
# Or, if .csv file, use this
my_data <- read.csv(file.choose())</code></pre>
<p>Here, we’ll use an example data set, which contains the weight of 10 mice before and after the treatment.</p>
<pre class="r"><code># Data in two numeric vectors
# ++++++++++++++++++++++++++
# Weight of the mice before treatment
before <-c(200.1, 190.9, 192.7, 213, 241.4, 196.9, 172.2, 185.5, 205.2, 193.7)
# Weight of the mice after treatment
after <-c(392.9, 393.2, 345.1, 393, 434, 427.9, 422, 383.9, 392.3, 352.2)
# Create a data frame
my_data <- data.frame( 
                group = rep(c("before", "after"), each = 10),
                weight = c(before,  after)
                )</code></pre>
<p><span class="question">We want to know, if there is any significant difference in the mean weights after treatment?</span></p>
</div>
<div id="check-your-data" class="section level2">
<h2>Check your data</h2>
<pre class="r"><code># Print all data
print(my_data)</code></pre>
<pre><code>    group weight
1  before  200.1
2  before  190.9
3  before  192.7
4  before  213.0
5  before  241.4
6  before  196.9
7  before  172.2
8  before  185.5
9  before  205.2
10 before  193.7
11  after  392.9
12  after  393.2
13  after  345.1
14  after  393.0
15  after  434.0
16  after  427.9
17  after  422.0
18  after  383.9
19  after  392.3
20  after  352.2</code></pre>
<p>Compute summary statistics (mean and sd) by groups using the dplyr package.</p>
<ul>
<li>To install <strong>dplyr</strong> package, type this:</li>
</ul>
<pre class="r"><code>install.packages("dplyr")</code></pre>
<ul>
<li>Compute summary statistics by groups:</li>
</ul>
<pre class="r"><code>library("dplyr")
group_by(my_data, group) %>%
  summarise(
    count = n(),
    mean = mean(weight, na.rm = TRUE),
    sd = sd(weight, na.rm = TRUE)
  )</code></pre>
<pre><code>Source: local data frame [2 x 4]
   group count   mean       sd
  (fctr) (int)  (dbl)    (dbl)
1  after    10 393.65 29.39801
2 before    10 199.16 18.47354</code></pre>
</div>
<div id="visualize-your-data-using-box-plots" class="section level2">
<h2>Visualize your data using box plots</h2>
<p>To use R base graphs read this: <a href="https://www.sthda.com/english/english/wiki/r-base-graphs">R base graphs</a>. Here, we’ll use the <a href="https://www.sthda.com/english/english/wiki/ggpubr-r-package-ggplot2-based-publication-ready-plots"><strong>ggpubr</strong> R package</a> for an easy ggplot2-based data visualization.</p>
<ul>
<li>Install the latest version of ggpubr from GitHub as follow (recommended):</li>
</ul>
<pre class="r"><code># Install
if(!require(devtools)) install.packages("devtools")
devtools::install_github("kassambara/ggpubr")</code></pre>
<ul>
<li>Or, install from CRAN as follow:</li>
</ul>
<pre class="r"><code>install.packages("ggpubr")</code></pre>
<ul>
<li>Visualize your data:</li>
</ul>
<pre class="r"><code># Plot weight by group and color by group
library("ggpubr")
ggboxplot(my_data, x = "group", y = "weight", 
          color = "group", palette = c("#00AFBB", "#E7B800"),
          order = c("before", "after"),
          ylab = "Weight", xlab = "Groups")</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/paired-t-test-box-plot-1.png" alt="Paired Samples T-test in R" width="336" style="margin-bottom:10px;" />
<p class="caption">
Paired Samples T-test in R
</p>
</div>
<p><span class="warning">Box plots show you the increase, but lose the paired information. You can use the function <strong>plot.paired</strong>() [in <strong>pairedData</strong> package] to plot paired data (“before - after” plot).</span></p>
<ul>
<li>Install pairedData package:</li>
</ul>
<pre class="r"><code>install.packages("PairedData")</code></pre>
<ul>
<li>Plot paired data:</li>
</ul>
<pre class="r"><code># Subset weight data before treatment
before <- subset(my_data,  group == "before", weight,
                 drop = TRUE)
# subset weight data after treatment
after <- subset(my_data,  group == "after", weight,
                 drop = TRUE)
# Plot paired data
library(PairedData)
pd <- paired(before, after)
plot(pd, type = "profile") + theme_bw()</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/paired-t-test-before-after-plot-1.png" alt="Paired Samples T-test in R" width="336" style="margin-bottom:10px;" />
<p class="caption">
Paired Samples T-test in R
</p>
</div>
</div>
<div id="preleminary-test-to-check-paired-t-test-assumptions" class="section level2">
<h2>Preleminary test to check paired t-test assumptions</h2>
<p><span class="question">Assumption 1: Are the two samples paired? </span></p>
<p>Yes, since the data have been collected from measuring twice the weight of the same mice.</p>
<p><span class="question"> Assumption 2: Is this a large sample?</span></p>
<p>No, because n < 30. Since the sample size is not large enough (less than 30), we need to check whether the differences of the pairs follow a <a href="https://www.sthda.com/english/english/wiki/normality-test-in-r">normal distribution</a>.</p>
<p><span class="question">How to check the normality?</span></p>
<p>Use Shapiro-Wilk normality test as described at: <a href="https://www.sthda.com/english/english/wiki/normality-test-in-r">Normality Test in R</a>.</p>
<ul>
<li>Null hypothesis: the data are normally distributed</li>
<li>Alternative hypothesis: the data are not normally distributed</li>
</ul>
<pre class="r"><code># compute the difference
d <- with(my_data, 
        weight[group == "before"] - weight[group == "after"])
# Shapiro-Wilk normality test for the differences
shapiro.test(d) # => p-value = 0.6141</code></pre>
<p><span class="success">From the output, the p-value is greater than the significance level 0.05 implying that the distribution of the differences (d) are not significantly different from normal distribution. In other words, we can assume the normality.</span></p>
<p><span class="warning">Note that, if the data are not normally distributed, it’s recommended to use the non parametric <a href="https://www.sthda.com/english/english/wiki/paired-samples-wilcoxon-test-in-r"><strong>paired two-samples Wilcoxon test</strong></a>.</span></p>
</div>
<div id="compute-paired-samples-t-test" class="section level2">
<h2>Compute paired samples t-test</h2>
<p><span class="question">Question : Is there any significant changes in the weights of mice after treatment?</span></p>
<p><strong>1) Compute paired t-test - Method 1</strong>: The data are saved in two different numeric vectors.</p>
<pre class="r"><code># Compute t-test
res <- t.test(before, after, paired = TRUE)
res</code></pre>
<pre><code>
    Paired t-test
data:  before and after
t = -20.883, df = 9, p-value = 6.2e-09
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -215.5581 -173.4219
sample estimates:
mean of the differences 
                -194.49 </code></pre>
<p><strong>2) Compute paired t-test - Method 2</strong>: The data are saved in a data frame.</p>
<pre class="r"><code># Compute t-test
res <- t.test(weight ~ group, data = my_data, paired = TRUE)
res</code></pre>
<pre><code>
    Paired t-test
data:  weight by group
t = 20.883, df = 9, p-value = 6.2e-09
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 173.4219 215.5581
sample estimates:
mean of the differences 
                 194.49 </code></pre>
<p><span class="notice">As you can see, the two methods give the same results.</span></p>
<br/>
<div class="block">
<p>In the result above :</p>
<ul>
<li><strong>t</strong> is the <strong>t-test statistic</strong> value (t = 20.88),</li>
<li><strong>df</strong> is the degrees of freedom (df= 9),</li>
<li><strong>p-value</strong> is the significance level of the <strong>t-test</strong> (p-value = 6.210^{-9}).</li>
<li><strong>conf.int</strong> is the <strong>confidence interval</strong> (conf.int) of the mean differences at 95% is also shown (conf.int= [173.42, 215.56])</li>
<li><strong>sample estimates</strong> is the mean differences between pairs (mean = 194.49).</li>
</ul>
</div>
<p><br/></p>
<br/>
<div class="notice">
<p>Note that:</p>
<ul>
<li>if you want to test whether the average weight before treatment is less than the average weight after treatment, type this:</li>
</ul>
<pre class="r"><code>t.test(weight ~ group, data = my_data, paired = TRUE,
        alternative = "less")</code></pre>
<ul>
<li>Or, if you want to test whether the average weight before treatment is greater than the average weight after treatment, type this</li>
</ul>
<pre class="r"><code>t.test(weight ~ group, data = my_data, paired = TRUE,
       alternative = "greater")</code></pre>
</div>
<p><br/></p>
</div>
<div id="interpretation-of-the-result" class="section level2">
<h2>Interpretation of the result</h2>
<p><span class="success">The <strong>p-value</strong> of the test is 6.210^{-9}, which is less than the significance level alpha = 0.05. We can then reject null hypothesis and conclude that the average weight of the mice before treatment is significantly different from the average weight after treatment with a <strong>p-value</strong> = 6.210^{-9}.</span></p>
</div>
<div id="access-to-the-values-returned-by-t.test-function" class="section level2">
<h2>Access to the values returned by t.test() function</h2>
<p>The result of <strong>t.test()</strong> function is a list containing the following components:</p>
<br/>
<div class="block">
<ul>
<li><strong>statistic</strong>: the value of the <strong>t test statistics</strong></li>
<li><strong>parameter</strong>: the <strong>degrees of freedom</strong> for the <strong>t test statistics</strong></li>
<li><strong>p.value</strong>: the <strong>p-value</strong> for the test</li>
<li><strong>conf.int</strong>: a <strong>confidence interval</strong> for the mean appropriate to the specified <strong>alternative hypothesis</strong>.</li>
<li><strong>estimate</strong>: the means of the two groups being compared (in the case of <strong>independent t test</strong>) or difference in means (in the case of <strong>paired t test</strong>).</li>
</ul>
</div>
<p><br/></p>
<p>The format of the <strong>R</strong> code to use for getting these values is as follow:</p>
<pre class="r"><code># printing the p-value
res$p.value</code></pre>
<pre><code>[1] 6.200298e-09</code></pre>
<pre class="r"><code># printing the mean
res$estimate</code></pre>
<pre><code>mean of the differences 
                 194.49 </code></pre>
<pre class="r"><code># printing the confidence interval
res$conf.int</code></pre>
<pre><code>[1] 173.4219 215.5581
attr(,"conf.level")
[1] 0.95</code></pre>
</div>
</div>
<div id="online-paired-t-test-calculator" class="section level1">
<h1>Online paired t-test calculator</h1>
<p>You can perform <strong>paired-samples t-test</strong>, <strong>online</strong>, without any installation by clicking the following link:</p>
<br/>
<div class="block">
<i class="fa - fa-cogs fa-4x valign_middle"></i> <a href="https://www.sthda.com/english/english/rsthda/paired-t-test.php">Online paired-samples t-test calculator</a>
</div>
<p><br/></p>
</div>
<div id="see-also" class="section level1">
<h1>See also</h1>
<p><a href="https://www.sthda.com/english/english/wiki/paired-samples-wilcoxon-test-in-r">Paired Samples Wilcoxon Test (non-parametric)</a></p>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.2.4). </span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
  (function () {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src  = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
    document.getElementsByTagName("head")[0].appendChild(script);
  })();
</script>
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 01:02:49 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Two-Way ANOVA Test in R]]></title>
			<link>https://www.sthda.com/english/wiki/two-way-anova-test-in-r</link>
			<guid>https://www.sthda.com/english/wiki/two-way-anova-test-in-r</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#what-is-two-way-anova-test">What is two-way ANOVA test?</a></li>
<li><a href="#two-way-anova-test-hypotheses">Two-way ANOVA test hypotheses</a></li>
<li><a href="#assumptions-of-two-way-anova-test">Assumptions of two-way ANOVA test</a></li>
<li><a href="#compute-two-way-anova-test-in-r-balanced-designs">Compute two-way ANOVA test in R: balanced designs</a><ul>
<li><a href="#import-your-data-into-r">Import your data into R</a></li>
<li><a href="#check-your-data">Check your data</a></li>
<li><a href="#visualize-your-data">Visualize your data</a></li>
<li><a href="#compute-two-way-anova-test">Compute two-way ANOVA test</a></li>
<li><a href="#interpret-the-results">Interpret the results</a></li>
<li><a href="#compute-some-summary-statistics">Compute some summary statistics</a></li>
<li><a href="#multiple-pairwise-comparison-between-the-means-of-groups">Multiple pairwise-comparison between the means of groups</a><ul>
<li><a href="#tukey-multiple-pairwise-comparisons">Tukey multiple pairwise-comparisons</a></li>
<li><a href="#multiple-comparisons-using-multcomp-package">Multiple comparisons using multcomp package</a></li>
<li><a href="#pairwise-t-test">Pairwise t-test</a></li>
</ul></li>
<li><a href="#check-anova-assumptions-test-validity">Check ANOVA assumptions: test validity?</a><ul>
<li><a href="#check-the-homogeneity-of-variance-assumption">Check the homogeneity of variance assumption</a></li>
<li><a href="#check-the-normality-assumpttion">Check the normality assumpttion</a></li>
</ul></li>
</ul></li>
<li><a href="#compute-two-way-anova-test-in-r-for-unbalanced-designs">Compute two-way ANOVA test in R for unbalanced designs</a></li>
<li><a href="#see-also">See also</a></li>
<li><a href="#read-more">Read more</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<div id="what-is-two-way-anova-test" class="section level1">
<h1>What is two-way ANOVA test?</h1>
<br/>
<div class="block">
<strong>Two-way</strong> <strong>ANOVA test</strong> is used to evaluate simultaneously the effect of two grouping variables (A and B) on a response variable.
</div>
<p><br/></p>
<p>The grouping variables are also known as factors. The different categories (groups) of a factor are called levels. The number of levels can vary between factors. The level combinations of factors are called cell.</p>
<br/>
<div class="warning">
<ul>
<li><p>When the sample sizes within cells are equal, we have the so-called <strong>balanced design</strong>. In this case the standard two-way ANOVA test can be applied.</p></li>
<li>When the sample sizes within each level of the independent variables are not the same (case of <strong>unbalanced designs</strong>), the ANOVA test should be handled differently.</li>
</ul>
</div>
<p><br/></p>
<p>This tutorial describes how to compute <strong>two-way ANOVA test</strong> in R software for balanced and unbalanced designs.</p>
<p><br/> <img src="https://www.sthda.com/english/sthda/RDoc/images/two-way-anova-test.png" alt="Two-Way ANOVA Test" /> <br/></p>
</div>

<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/pqs3" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/r-statistics-for-comparing-means.png" /><br/>
     Practical Statistics in R for Comparing Groups: Numerical Variables
      </a>
</div>
<div class="spacer"></div>


<div id="two-way-anova-test-hypotheses" class="section level1">
<h1>Two-way ANOVA test hypotheses</h1>
<ol style="list-style-type: decimal">
<li>There is no difference in the means of factor A</li>
<li>There is no difference in means of factor B</li>
<li>There is no interaction between factors A and B</li>
</ol>
<p>The alternative hypothesis for cases 1 and 2 is: the means are not equal.</p>
<p>The alternative hypothesis for case 3 is: there is an interaction between A and B.</p>
</div>
<div id="assumptions-of-two-way-anova-test" class="section level1">
<h1>Assumptions of two-way ANOVA test</h1>
<p>Two-way ANOVA, like all ANOVA tests, assumes that the observations within each cell are normally distributed and have equal variances. We’ll show you how to check these assumptions after fitting ANOVA.</p>
</div>
<div id="compute-two-way-anova-test-in-r-balanced-designs" class="section level1">
<h1>Compute two-way ANOVA test in R: balanced designs</h1>
<p><span class="success">Balanced designs correspond to the situation where we have equal sample sizes within levels of our independent grouping levels.</span></p>
<div id="import-your-data-into-r" class="section level2">
<h2>Import your data into R</h2>
<ol style="list-style-type: decimal">
<li><p><strong>Prepare your data</strong> as specified here: <a href="https://www.sthda.com/english/english/wiki/best-practices-for-preparing-your-data-set-for-r">Best practices for preparing your data set for R</a></p></li>
<li><p><strong>Save your data</strong> in an external .txt tab or .csv files</p></li>
<li><p><strong>Import your data into R</strong> as follow:</p></li>
</ol>
<pre class="r"><code># If .txt tab file, use this
my_data <- read.delim(file.choose())
# Or, if .csv file, use this
my_data <- read.csv(file.choose())</code></pre>
<p>Here, we’ll use the built-in R data set named <em>ToothGrowth</em>. It contains data from a study evaluating the effect of vitamin C on tooth growth in Guinea pigs. The experiment has been performed on 60 pigs, where each animal received one of three dose levels of vitamin C (0.5, 1, and 2 mg/day) by one of two delivery methods, (orange juice or ascorbic acid (a form of vitamin C and coded as VC). Tooth length was measured and a sample of the data is shown below.</p>
<pre class="r"><code># Store the data in the variable my_data
my_data <- ToothGrowth</code></pre>
</div>
<div id="check-your-data" class="section level2">
<h2>Check your data</h2>
<p>To get an idea of what the data look like, we display a random sample of the data using the function <strong>sample_n</strong>()[in <strong>dplyr</strong> package]. First, install dplyr if you don’t have it:</p>
<pre class="r"><code>install.packages("dplyr")</code></pre>
<pre class="r"><code># Show a random sample
set.seed(1234)
dplyr::sample_n(my_data, 10)</code></pre>
<pre><code>    len supp dose
38  9.4   OJ  0.5
36 10.0   OJ  0.5
37  8.2   OJ  0.5
50 27.3   OJ  1.0
59 29.4   OJ  2.0
1   4.2   VC  0.5
13 15.2   VC  1.0
56 30.9   OJ  2.0
27 26.7   VC  2.0
53 22.4   OJ  2.0</code></pre>
<pre class="r"><code># Check the structure
str(my_data)</code></pre>
<pre><code>'data.frame':   60 obs. of  3 variables:
 $ len : num  4.2 11.5 7.3 5.8 6.4 10 11.2 11.2 5.2 7 ...
 $ supp: Factor w/ 2 levels "OJ","VC": 2 2 2 2 2 2 2 2 2 2 ...
 $ dose: num  0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 ...</code></pre>
<p><span class="warning">From the output above, R considers “dose” as a numeric variable. We’ll convert it as a factor variable (i.e., grouping variable) as follow.</span></p>
<pre class="r"><code># Convert dose as a factor and recode the levels
# as "D0.5", "D1", "D2"
my_data$dose <- factor(my_data$dose, 
                  levels = c(0.5, 1, 2),
                  labels = c("D0.5", "D1", "D2"))
head(my_data)</code></pre>
<pre><code>   len supp dose
1  4.2   VC D0.5
2 11.5   VC D0.5
3  7.3   VC D0.5
4  5.8   VC D0.5
5  6.4   VC D0.5
6 10.0   VC D0.5</code></pre>
<p><span class="question"> Question: We want to know if tooth length depends on supp and dose.</span></p>
<ul>
<li>Generate frequency tables:</li>
</ul>
<pre class="r"><code>table(my_data$supp, my_data$dose)</code></pre>
<pre><code>    
     D0.5 D1 D2
  OJ   10 10 10
  VC   10 10 10</code></pre>
<p><span class="success">We have 2X3 design cells with the factors being supp and dose and 10 subjects in each cell. Here, we have a <strong>balanced design</strong>. In the next sections I’ll describe how to analyse data from balanced designs, since this is the simplest case.</span></p>
</div>
<div id="visualize-your-data" class="section level2">
<h2>Visualize your data</h2>
<p>Box plots and line plots can be used to visualize group differences:</p>
<ul>
<li><strong>Box plot</strong> to plot the data grouped by the combinations of the levels of the two factors.</li>
<li><p><strong>Two-way interaction plot</strong>, which plots the mean (or other summary) of the response for two-way combinations of factors, thereby illustrating possible interactions.</p></li>
<li><p>To use R base graphs read this: <a href="https://www.sthda.com/english/english/wiki/r-base-graphs">R base graphs</a>. Here, we’ll use the <a href="https://www.sthda.com/english/english/wiki/ggpubr-r-package-ggplot2-based-publication-ready-plots"><strong>ggpubr</strong> R package</a> for an easy ggplot2-based data visualization.</p></li>
<li><p>Install the latest version of ggpubr from GitHub as follow (recommended):</p></li>
</ul>
<pre class="r"><code># Install
if(!require(devtools)) install.packages("devtools")
devtools::install_github("kassambara/ggpubr")</code></pre>
<ul>
<li>Or, install from CRAN as follow:</li>
</ul>
<pre class="r"><code>install.packages("ggpubr")</code></pre>
<ul>
<li>Visualize your data with ggpubr:</li>
</ul>
<pre class="r"><code># Box plot with multiple groups
# +++++++++++++++++++++
# Plot tooth length ("len") by groups ("dose")
# Color box plot by a second group: "supp"
library("ggpubr")
ggboxplot(my_data, x = "dose", y = "len", color = "supp",
          palette = c("#00AFBB", "#E7B800"))</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/two-way-anova-box-plot-1.png" alt="Two-Way ANOVA Test in R" width="480" style="margin-bottom:10px;" />
<p class="caption">
Two-Way ANOVA Test in R
</p>
</div>
<pre class="r"><code># Line plots with multiple groups
# +++++++++++++++++++++++
# Plot tooth length ("len") by groups ("dose")
# Color box plot by a second group: "supp"
# Add error bars: mean_se
# (other values include: mean_sd, mean_ci, median_iqr, ....)
library("ggpubr")
ggline(my_data, x = "dose", y = "len", color = "supp",
       add = c("mean_se", "dotplot"),
       palette = c("#00AFBB", "#E7B800"))</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/two-way-anova-box-plot-2.png" alt="Two-Way ANOVA Test in R" width="480" style="margin-bottom:10px;" />
<p class="caption">
Two-Way ANOVA Test in R
</p>
</div>
<p>If you still want to use R base graphs, type the following scripts:</p>
<pre class="r"><code># Box plot with two factor variables
boxplot(len ~ supp * dose, data=my_data, frame = FALSE, 
        col = c("#00AFBB", "#E7B800"), ylab="Tooth Length")
# Two-way interaction plot
interaction.plot(x.factor = my_data$dose, trace.factor = my_data$supp, 
                 response = my_data$len, fun = mean, 
                 type = "b", legend = TRUE, 
                 xlab = "Dose", ylab="Tooth Length",
                 pch=c(1,19), col = c("#00AFBB", "#E7B800"))</code></pre>
<p>Arguments used for the function <strong>interaction.plot</strong>():</p>
<br/>
<div class="block">
<ul>
<li><strong>x.factor</strong>: the factor to be plotted on x axis.</li>
<li><strong>trace.factor</strong>: the factor to be plotted as lines</li>
<li><strong>response</strong>: a numeric variable giving the response</li>
<li><strong>type</strong>: the type of plot. Allowed values include <strong>p</strong> (for point only), <strong>l</strong> (for line only) and <strong>b</strong> (for both point and line).</li>
</ul>
</div>
<p><br/></p>
</div>
<div id="compute-two-way-anova-test" class="section level2">
<h2>Compute two-way ANOVA test</h2>
<p><span class="question">We want to know if tooth length depends on supp and dose.</span></p>
<p>The R function <strong>aov</strong>() can be used to answer this question. The function <strong>summary.aov</strong>() is used to summarize the analysis of variance model.</p>
<pre class="r"><code>res.aov2 <- aov(len ~ supp + dose, data = my_data)
summary(res.aov2)</code></pre>
<pre><code>            Df Sum Sq Mean Sq F value   Pr(>F)    
supp         1  205.4   205.4   14.02 0.000429 ***
dose         2 2426.4  1213.2   82.81  < 2e-16 ***
Residuals   56  820.4    14.7                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</code></pre>
<p>The output includes the columns <em>F value</em> and <em>Pr(>F)</em> corresponding to the p-value of the test.</p>
<p><span class="success">From the ANOVA table we can conclude that both <em>supp</em> and <em>dose</em> are statistically significant. <em>dose</em> is the most significant factor variable. These results would lead us to believe that changing delivery methods (supp) or the dose of vitamin C, will impact significantly the mean tooth length.</span></p>
<p><span class = "warning">Not the above fitted model is called <strong>additive model</strong>. It makes an assumption that the two factor variables are independent. If you think that these two variables might interact to create an synergistic effect, replace the plus symbol (+) by an asterisk (*), as follow.</span></p>
<pre class="r"><code># Two-way ANOVA with interaction effect
# These two calls are equivalent
res.aov3 <- aov(len ~ supp * dose, data = my_data)
res.aov3 <- aov(len ~ supp + dose + supp:dose, data = my_data)
summary(res.aov3)</code></pre>
<pre><code>            Df Sum Sq Mean Sq F value   Pr(>F)    
supp         1  205.4   205.4  15.572 0.000231 ***
dose         2 2426.4  1213.2  92.000  < 2e-16 ***
supp:dose    2  108.3    54.2   4.107 0.021860 *  
Residuals   54  712.1    13.2                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</code></pre>
<p><span class="success">It can be seen that the two main effects (supp and dose) are statistically significant, as well as their interaction.</span></p>
<p><span class="warning">Note that, in the situation where the interaction is not significant you should use the additive model.</span></p>
</div>
<div id="interpret-the-results" class="section level2">
<h2>Interpret the results</h2>
<p>From the ANOVA results, you can conclude the following, based on the p-values and a significance level of 0.05:</p>
<ul>
<li>the p-value of supp is 0.000429 (significant), which indicates that the levels of supp are associated with significant different tooth length.</li>
<li>the p-value of dose is < 2e-16 (significant), which indicates that the levels of dose are associated with significant different tooth length.</li>
<li>the p-value for the interaction between supp*dose is 0.02 (significant), which indicates that the relationships between dose and tooth length depends on the supp method.</li>
</ul>
</div>
<div id="compute-some-summary-statistics" class="section level2">
<h2>Compute some summary statistics</h2>
<ul>
<li>Compute mean and SD by groups using dplyr R package:</li>
</ul>
<pre class="r"><code>require("dplyr")
group_by(my_data, supp, dose) %>%
  summarise(
    count = n(),
    mean = mean(len, na.rm = TRUE),
    sd = sd(len, na.rm = TRUE)
  )</code></pre>
<pre><code>Source: local data frame [6 x 5]
Groups: supp [?]
    supp   dose count  mean       sd
  (fctr) (fctr) (int) (dbl)    (dbl)
1     OJ   D0.5    10 13.23 4.459709
2     OJ     D1    10 22.70 3.910953
3     OJ     D2    10 26.06 2.655058
4     VC   D0.5    10  7.98 2.746634
5     VC     D1    10 16.77 2.515309
6     VC     D2    10 26.14 4.797731</code></pre>
<ul>
<li>It’s also possible to use the function <strong>model.tables</strong>() as follow:</li>
</ul>
<pre class="r"><code>model.tables(res.aov3, type="means", se = TRUE)</code></pre>
</div>
<div id="multiple-pairwise-comparison-between-the-means-of-groups" class="section level2">
<h2>Multiple pairwise-comparison between the means of groups</h2>
<p>In ANOVA test, a significant p-value indicates that some of the group means are different, but we don’t know which pairs of groups are different.</p>
<p>It’s possible to perform multiple pairwise-comparison, to determine if the mean difference between specific pairs of group are statistically significant.</p>
<div id="tukey-multiple-pairwise-comparisons" class="section level3">
<h3>Tukey multiple pairwise-comparisons</h3>
<p>As the ANOVA test is significant, we can compute <strong>Tukey HSD</strong> (Tukey Honest Significant Differences, R function: <strong>TukeyHSD</strong>()) for performing multiple pairwise-comparison between the means of groups. The function <strong>TukeyHD</strong>() takes the fitted ANOVA as an argument.</p>
<p><span class="warning"> We don’t need to perform the test for the “supp” variable because it has only two levels, which have been already proven to be significantly different by ANOVA test. Therefore, the Tukey HSD test will be done only for the factor variable “dose”.</span></p>
<pre class="r"><code>TukeyHSD(res.aov3, which = "dose")</code></pre>
<pre><code>  Tukey multiple comparisons of means
    95% family-wise confidence level
Fit: aov(formula = len ~ supp + dose + supp:dose, data = my_data)
$dose
          diff       lwr       upr   p adj
D1-D0.5  9.130  6.362488 11.897512 0.0e+00
D2-D0.5 15.495 12.727488 18.262512 0.0e+00
D2-D1    6.365  3.597488  9.132512 2.7e-06</code></pre>
<ul>
<li><strong>diff</strong>: difference between means of the two groups</li>
<li><strong>lwr</strong>, <strong>upr</strong>: the lower and the upper end point of the confidence interval at 95% (default)</li>
<li><strong>p adj</strong>: p-value after adjustment for the multiple comparisons.</li>
</ul>
<p><span class="notice">It can be seen from the output, that all pairwise comparisons are significant with an adjusted p-value < 0.05.</span></p>
</div>
<div id="multiple-comparisons-using-multcomp-package" class="section level3">
<h3>Multiple comparisons using multcomp package</h3>
<p>It’s possible to use the function <strong>glht</strong>() [in <strong>multcomp</strong> package] to perform multiple comparison procedures for an ANOVA. <strong>glht</strong> stands for general linear hypothesis tests. The simplified format is as follow:</p>
<pre class="r"><code>glht(model, lincft)</code></pre>
<ul>
<li><strong>model</strong>: a fitted model, for example an object returned by <strong>aov</strong>().</li>
<li><strong>lincft</strong>(): a specification of the linear hypotheses to be tested. Multiple comparisons in ANOVA models are specified by objects returned from the function <strong>mcp</strong>().</li>
</ul>
<p>Use glht() to perform multiple pairwise-comparisons:</p>
<pre class="r"><code>library(multcomp)
summary(glht(res.aov2, linfct = mcp(dose = "Tukey")))</code></pre>
<pre><code>
     Simultaneous Tests for General Linear Hypotheses
Multiple Comparisons of Means: Tukey Contrasts
Fit: aov(formula = len ~ supp + dose, data = my_data)
Linear Hypotheses:
               Estimate Std. Error t value Pr(>|t|)    
D1 - D0.5 == 0    9.130      1.210   7.543   <1e-05 ***
D2 - D0.5 == 0   15.495      1.210  12.802   <1e-05 ***
D2 - D1 == 0      6.365      1.210   5.259   <1e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Adjusted p values reported -- single-step method)</code></pre>
</div>
<div id="pairwise-t-test" class="section level3">
<h3>Pairwise t-test</h3>
<p>The function <strong>pairwise.t.test</strong>() can be also used to calculate pairwise comparisons between group levels with corrections for multiple testing.</p>
<pre class="r"><code>pairwise.t.test(my_data$len, my_data$dose,
                p.adjust.method = "BH")</code></pre>
<pre><code>
    Pairwise comparisons using t tests with pooled SD 
data:  my_data$len and my_data$dose 
   D0.5    D1     
D1 1.0e-08 -      
D2 4.4e-16 1.4e-05
P value adjustment method: BH </code></pre>
</div>
</div>
<div id="check-anova-assumptions-test-validity" class="section level2">
<h2>Check ANOVA assumptions: test validity?</h2>
<p>ANOVA assumes that the data are normally distributed and the variance across groups are homogeneous. We can check that with some diagnostic plots.</p>
<div id="check-the-homogeneity-of-variance-assumption" class="section level3">
<h3>Check the homogeneity of variance assumption</h3>
<p>The <strong>residuals versus fits plot</strong> is used to check the homogeneity of variances. In the plot below, there is no evident relationships between residuals and fitted values (the mean of each groups), which is good. So, we can assume the homogeneity of variances.</p>
<pre class="r"><code># 1. Homogeneity of variances
plot(res.aov3, 1)</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/two-way-anova-residuals-vs-fits-1.png" alt="Two-Way ANOVA Test in R" width="384" style="margin-bottom:10px;" />
<p class="caption">
Two-Way ANOVA Test in R
</p>
</div>
<p><span class="error"> Points 32 and 23 are detected as outliers, which can severely affect normality and homogeneity of variance. It can be useful to remove outliers to meet the test assumptions.</span></p>
<p>Use the <strong>Levene’s test</strong> to check the <strong>homogeneity of variances</strong>. The function <strong>leveneTest</strong>() [in <strong>car</strong> package] will be used:</p>
<pre class="r"><code>library(car)
leveneTest(len ~ supp*dose, data = my_data)</code></pre>
<pre><code>Levene's Test for Homogeneity of Variance (center = median)
      Df F value Pr(>F)
group  5  1.7086 0.1484
      54               </code></pre>
<p><span class="success">From the output above we can see that the p-value is not less than the significance level of 0.05. This means that there is no evidence to suggest that the variance across groups is statistically significantly different. Therefore, we can assume the homogeneity of variances in the different treatment groups.</span></p>
</div>
<div id="check-the-normality-assumpttion" class="section level3">
<h3>Check the normality assumpttion</h3>
<p><strong>Normality plot of the residuals</strong>. In the plot below, the quantiles of the residuals are plotted against the quantiles of the normal distribution. A 45-degree reference line is also plotted.</p>
<p>The normal probability plot of residuals is used to verify the assumption that the residuals are normally distributed.</p>
<p>The normal probability plot of the residuals should approximately follow a straight line.</p>
<pre class="r"><code># 2. Normality
plot(res.aov3, 2)</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/statistics/two-way-anova-normality-plot-1.png" alt="Two-Way ANOVA Test in R" width="384" style="margin-bottom:10px;" />
<p class="caption">
Two-Way ANOVA Test in R
</p>
</div>
<p><span class="success">As all the points fall approximately along this reference line, we can assume normality.</span></p>
<p>The conclusion above, is supported by the <strong>Shapiro-Wilk test</strong> on the ANOVA residuals (W = 0.98, p = 0.5) which finds no indication that normality is violated.</p>
<pre class="r"><code># Extract the residuals
aov_residuals <- residuals(object = res.aov3)
# Run Shapiro-Wilk test
shapiro.test(x = aov_residuals )</code></pre>
<pre><code>
    Shapiro-Wilk normality test
data:  aov_residuals
W = 0.98499, p-value = 0.6694</code></pre>
</div>
</div>
</div>
<div id="compute-two-way-anova-test-in-r-for-unbalanced-designs" class="section level1">
<h1>Compute two-way ANOVA test in R for unbalanced designs</h1>
<p>An <strong>unbalanced design</strong> has unequal numbers of subjects in each group.</p>
<p>There are three fundamentally different ways to run an ANOVA in an unbalanced design. They are known as Type-I, Type-II and Type-III sums of squares. To keep things simple, note that The recommended method are the Type-III sums of squares.</p>
<p><span class="warning">The three methods give the same result when the design is balanced. However, when the design is unbalanced, they don’t give the same results.</span></p>
<p>The function <strong>Anova</strong>() [in <strong>car</strong> package] can be used to compute two-way ANOVA test for unbalanced designs.</p>
<p>First install the package on your computer. In R, type <strong>install.packages</strong>(“car”). Then:</p>
<pre class="r"><code>library(car)
my_anova <- aov(len ~ supp * dose, data = my_data)
Anova(my_anova, type = "III")</code></pre>
<pre><code>Anova Table (Type III tests)
Response: len
             Sum Sq Df F value    Pr(>F)    
(Intercept) 1750.33  1 132.730 3.603e-16 ***
supp         137.81  1  10.450  0.002092 ** 
dose         885.26  2  33.565 3.363e-10 ***
supp:dose    108.32  2   4.107  0.021860 *  
Residuals    712.11 54                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</code></pre>
</div>
<div id="see-also" class="section level1">
<h1>See also</h1>
<ul>
<li>Analysis of variance (ANOVA, parametric):
<ul>
<li><a href="https://www.sthda.com/english/english/wiki/one-way-anova-test-in-r">One-Way ANOVA Test in R</a></li>
<li><a href="https://www.sthda.com/english/english/wiki/manova-test-in-r-multivariate-analysis-of-variance">MANOVA Test in R: Multivariate Analysis of Variance</a></li>
</ul></li>
<li><a href="https://www.sthda.com/english/english/wiki/kruskal-wallis-test-in-r">Kruskal-Wallis Test in R (non parametric alternative to one-way ANOVA)</a></li>
</ul>
</div>
<div id="read-more" class="section level1">
<h1>Read more</h1>
<ul>
<li><a href="http://www.statmethods.net/stats/anova.html">Quick-R: ANOVA/MANOVA</a></li>
<li><a href="http://www.statmethods.net/stats/anovaAssumptions.html">Quick-R: ANOVA Assumptions</a></li>
<li><a href="http://personality-project.org/r/r.guide/r.anova.html">R and Analysis of Variance</a></li>
</ul>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.2.4). </span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 01:01:55 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[t test formula]]></title>
			<link>https://www.sthda.com/english/wiki/t-test-formula</link>
			<guid>https://www.sthda.com/english/wiki/t-test-formula</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#t-test-definition">t-test definition</a></li>
<li><a href="#one-sample-t-test-formula">One-sample t-test formula</a></li>
<li><a href="#independent-two-sample-t-test">Independent two sample t-test</a><ul>
<li><a href="#what-is-independent-t-test">What is independent t-test ?</a></li>
<li><a href="#independent-t-test-formula">Independent t-test formula</a></li>
</ul></li>
<li><a href="#paired-sample-t-test">Paired sample t-test</a><ul>
<li><a href="#what-is-paired-t-test">What is paired t-test ?</a></li>
<li><a href="#paired-t-test-formula">Paired t-test formula</a></li>
</ul></li>
<li><a href="#online-t-test-calculator">Online t-test calculator</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<div id="t-test-definition" class="section level1">
<h1>t-test definition</h1>
<p><strong>Student t test</strong> is a <strong>statistical test</strong> which is widely used to compare the mean of two groups of samples. It is therefore to evaluate whether the means of the two sets of data are statistically <strong>significantly</strong> different from each other.</p>
<p>There are many types of <strong>t test</strong> :</p>
<ul>
<li>The <strong>one-sample t-test</strong>, used to compare the mean of a population with a theoretical value.</li>
<li>The <strong>unpaired two sample t-test</strong>, used to compare the mean of two <strong>independent samples</strong>.</li>
<li>The <strong>paired t-test</strong>, used to compare the means between two related groups of samples.</li>
</ul>
<p>The aim of this article is to describe the different <strong>t test formula</strong>. <strong>Student’s t-test</strong> is a <strong>parametric test</strong> as the <strong>formula</strong> depends on the <strong>mean</strong> and the <strong>standard deviation</strong> of the data being compared.</p>
<div class="block">
<i class="fa - fa-cogs fa-4x valign_middle"></i> Note that an online <strong>t-test calculator</strong> is available <a href="https://www.sthda.com/english/english/rsthda/rsthda.php">here</a> to compute <strong>t-test statistics</strong> without any installation.
</div>
</div>

<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/pqs3" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/r-statistics-for-comparing-means.png" /><br/>
     Practical Statistics in R for Comparing Groups: Numerical Variables
      </a>
</div>
<div class="spacer"></div>

<div id="one-sample-t-test-formula" class="section level1">
<h1>One-sample t-test formula</h1>
<p>As mentioned above, <strong>one-sample t-test</strong> is used to compare the mean of a population to a specified <strong>theoretical mean</strong> (<span class="math">\(\mu\)</span>).</p>
<p>Let X represents a set of values with size n, with <strong>mean</strong> m and with <strong>standard deviation</strong> S. The comparison of the <strong>observed mean (m) of the population</strong> to a <strong>theoretical value</strong> <span class="math">\(\mu\)</span> is performed with the formula below :</p>
<p><span class="math">\[
t = \frac{m-\mu}{s/\sqrt{n}}
\]</span></p>
<p>To evaluate whether the difference is statistically significant, you first have to read in <a href="https://www.sthda.com/english/english/wiki/t-test-table"><strong>t test table</strong></a> the <strong>critical value of Student’s t distribution</strong> corresponding to the <strong>significance level alpha</strong> of your choice (5%). The <strong>degrees of freedom</strong> (df) used in this test are :</p>
<p><span class="math">\[ df = n - 1 \]</span></p>
<p><span class="success"> If the absolute value of the <strong>t-test statistics</strong> (|t|) is greater than the critical value, then the difference is significant. Otherwise it isn’t. The <strong>level of significance</strong> or (<strong>p-value</strong>) corresponds to the risk indicated by the <a href="https://www.sthda.com/english/english/wiki/t-test-table"><strong>t test table</strong></a> for the calculated |t| value.</span></p>
<p><span class="notice">The <strong>t test</strong> can be used only when the data are normally distributed.</span></p>
</div>
<div id="independent-two-sample-t-test" class="section level1">
<h1>Independent two sample t-test</h1>
<div id="what-is-independent-t-test" class="section level2">
<h2>What is independent t-test ?</h2>
<p><strong>Independent (or unpaired two sample) t-test</strong> is used to compare the means of two unrelated groups of samples.</p>
<p>As an example, we have a cohort of 100 individuals (50 women and 50 men). The question is to test whether the average weight of women is significantly different from that of men?</p>
<p>In this case, we have two independents groups of samples and <strong>unpaired t-test</strong> can be used to test whether the means are different.</p>
</div>
<div id="independent-t-test-formula" class="section level2">
<h2>Independent t-test formula</h2>
<ul>
<li>Let A and B represent the two groups to compare.
</li>
<li>Let <span class="math">\(m_A\)</span> and <span class="math">\(m_B\)</span> represent the means of groups A and B, respectively.</li>
<li>Let <span class="math">\(n_A\)</span> and <span class="math">\(n_B\)</span> represent the sizes of group A and B, respectively.</li>
</ul>
<p>The <strong>t test statistic value</strong> to test whether the means are different can be calculated as follow :</p>
<p><span class="math">\[ 
t = \frac{m_A - m_B}{\sqrt{ \frac{S^2}{n_A} + \frac{S^2}{n_B} }} 
\]</span></p>
<p><span class="math">\(S^2\)</span> is an estimator of the common <strong>variance</strong> of the two samples. It can be calculated as follow :</p>
<p><span class="math">\[
S^2 = \frac{\sum{(x-m_A)^2}+\sum{(x-m_B)^2}}{n_A+n_B-2}
\]</span></p>
<p>Once <strong>t-test statistic value</strong> is determined, you have to read in <a href="https://www.sthda.com/english/english/wiki/t-test-table"><strong>t-test table</strong></a> the <strong>critical value of Student’s t distribution</strong> corresponding to the <strong>significance level alpha</strong> of your choice (5%). The <strong>degrees of freedom</strong> (df) used in this test are :</p>
<p><span class="math">\[ df = n_A + n_B -2 \]</span></p>
<p><span class="success"> If the absolute value of the <strong>t-test statistics</strong> (|t|) is greater than the critical value, then the difference is significant. Otherwise it isn’t. The <strong>level of significance</strong> or (<strong>p-value</strong>) corresponds to the risk indicated by the <a href="https://www.sthda.com/english/english/wiki/t-test-table"><strong>t-test table</strong></a> for the calculated |t| value.</span></p>
<p><span class="warning"> The test can be used only when the two groups of samples (A and B) being compared follow bivariate <strong>normal distribution</strong> with equal <strong>variances</strong>. </span></p>
<p>If the variances of the two groups being compared are different, the <a href="https://www.sthda.com/english/english/wiki/welch-t-test"><strong>Welch t test</strong></a> can be used.</p>
</div>
</div>
<div id="paired-sample-t-test" class="section level1">
<h1>Paired sample t-test</h1>
<div id="what-is-paired-t-test" class="section level2">
<h2>What is paired t-test ?</h2>
<p><strong>Paired Student’s t-test</strong> is used to compare the means of two related samples. That is when you have two values (pair of values) for the same samples.</p>
<p>For example, 20 mice received a treatment X for 3 months. The question is to test whether the treatment X has an impact on the weight of the mice at the end of the 3 months treatment. The weight of the 20 mice has been measured before and after the treatment. This gives us 20 sets of values before treatment and 20 sets of values after treatment from measuring twice the weight of the same mice.</p>
<p>In this case, <strong>paired t-test</strong> can be used as the two sets of values being compared are related. We have a pair of values for each mouse (one before and the other after treatment).</p>
</div>
<div id="paired-t-test-formula" class="section level2">
<h2>Paired t-test formula</h2>
<p>To compare the means of the two paired sets of data, the differences between all pairs must be, first, calculated.</p>
<p>Let d represents the differences between all pairs. The average of the difference d is compared to 0. If there is any significant difference between the two pairs of samples, then the mean of d is expected to be far from 0.</p>
<p><strong>t test statistisc value</strong> can be calculated as follow :</p>
<p><span class="math">\[
t = \frac{m}{s/\sqrt{n}}
\]</span></p>
<p><strong>m</strong> and <strong>s</strong> are the <strong>mean</strong> and the <strong>standard deviation</strong> of the difference (d), respectively. <strong>n</strong> is the size of d.</p>
<p>Once <strong>t value</strong> is determined, you have to read in <a href="https://www.sthda.com/english/english/wiki/t-test-table"><strong>t-test table</strong></a> the <strong>critical value of Student’s t distribution</strong> corresponding to the <strong>significance level alpha</strong> of your choice (5%). The <strong>degrees of freedom</strong> (df) used in this test are :</p>
<p><span class="math">\[ df = n - 1 \]</span></p>
<p><span class="success"> If the absolute value of the <strong>t-test statistics</strong> (|t|) is greater than the critical value, then the difference is significant. Otherwise it isn’t. The <strong>level of significance</strong> or (<strong>p-value</strong>) corresponds to the risk indicated by the <a href="https://www.sthda.com/english/english/wiki/t-test-table"><strong>t-test table</strong></a> for the calculated |t| value.</span></p>
<p><span class="warning"> The test can be used only when the difference d is normally distributed. </span></p>
</div>
</div>
<div id="online-t-test-calculator" class="section level1">
<h1>Online t-test calculator</h1>
<p>You no longer need SPSS or Excel to perform <strong>t-test</strong>.</p>
<p><span class="success"> An <strong>online t-test calculator</strong> is available <a href="https://www.sthda.com/english/english/rsthda/rsthda.php">here</a> to perform <strong>Student’s t-test</strong> without any installation.</span></p>
<p>Depending on the types of <strong>Student’s t-test</strong> you want to do, click the following links :</p>
<ul>
<li><a href="https://www.sthda.com/english/english/rsthda/one-sample-t-test.php">One-sample t-test</a>
</li>
<li><a href="https://www.sthda.com/english/english/rsthda/unpaired-t-test.php">Independent sample t-test</a>
</li>
<li><a href="https://www.sthda.com/english/english/rsthda/paired-t-test.php">Paired samples t-test</a></li>
</ul>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been done using R (ver. 3.1.0). </span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('h1').addClass('wiki_paragraph1');
    jQuery('h2').addClass('wiki_paragraph2');
    jQuery('h3').addClass('wiki_paragraph3');
    jQuery('h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
  (function () {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src  = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
    document.getElementsByTagName("head")[0].appendChild(script);
  })();
</script>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 00:59:31 +0200</pubDate>
			
		</item>
		
	</channel>
</rss>
