---
title: "Beta-diversity Analysis with hagis"
author: "Austin McCoy"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Beta-diversity Analysis with hagis}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
  %\VignetteDepends{ape}
  %\VignetteDepends{ggplot2}
  %\VignetteDepends{vegan}
  %\VignetteDepends{dplyr}
  %\VignetteDepends{stats}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

required <- c("ape", "vegan", "dplyr")

if (!all(sapply(required, requireNamespace, quietly = TRUE)))
  knitr::opts_chunk$set(eval = FALSE)
data.table::setDTthreads(1L)
```

# Load Packages

These packages are necessary for this analysis to be conducted.

```{r libraries, message=FALSE, warning=FALSE}
library("ape")
library("vegan")
library("dplyr")
library("hagis")
library("ggplot2")
```

Import the data to be used in analysis.
These example data are included in {hagis} and so when loading {hagis} they become available in your R session.

```{r load-data}
head(P_sojae_survey) # survey sample data

head(sample_meta) # metatada about the sample collection locations
```

This removes the "MPS17\_" from the isolates, so that they will be read as numeric instead of character.
The next step removes the "Rps " from the gene names, so that they will be read as numeric instead of character.

```{r clean-data}
P_sojae_survey$Isolate <-
  gsub(pattern = "MPS17_",
       replacement = "",
       x = P_sojae_survey$Isolate)
P_sojae_survey$Rps <-
  gsub(pattern = "Rps ",
       replacement = "",
       x = P_sojae_survey$Rps)
```

Set up the {hagis} arguments for analysis.
Please see `vignette("hagis")` for more details on how to specify arguments for the functions in this package.

```{r hagis-arguments}
hagis_args <- list(
  x = P_sojae_survey,
  cutoff = 60,
  control = "susceptible",
  sample = "Isolate",
  gene = "Rps",
  perc_susc = "perc.susc"
)
```

# Convert the Dataset to a Binary Data Matrix

Using `create_binary_matrix()` transforms the data so that it is in the correct format (binary data matrix) for PCOA analysis.

```{r create-matrix}
P_sojae_survey.matrix <- do.call(create_binary_matrix, hagis_args)

P_sojae_survey.matrix
```

The `P_sojae_survey.matrix` object contains the RPS genes numbered as rows and the columns are numbered isolates.
A "1" indicates the isolate caused disease on the RPS gene, and a "0" means it did not.

# Perform Principle Coordinates Analysis (PCOA)

The following code will transpose the `P_sojae_survey.matrix` and then calculate the Jaccard distances for each isolate.
Jaccard distance calculations need to be used as pathotype data is presence/absence for virulence.
Lastly, PCOA is performed to identify the variance explained by each principal coordinate.
This will be used later to visualize and identify distance pathotype groupings by geographic location.
In this example, Jaccard distances are used as this is presence/absence data.

```{r distance-matrix}
P_sojae_survey.matrix.jaccard <-
  vegdist(P_sojae_survey.matrix, "jaccard", na.rm = TRUE)
```

After performing the principal coordinates analysis, we see that the scree plot says that about 70% of the variation in Jaccard distances are explained within the first two dimensions (*i.e.*, axes).
This is good.
Usually a good rule of thumb is that if the second dimension is roughly half variation explained in the first dimension you don't need to look further at the third or n+1 dimensions.

```{r barplot}
princoor.pathotype <- pcoa(P_sojae_survey.matrix.jaccard) 

barplot(princoor.pathotype$values$Relative_eig[1:10])
```

Now we can calculate the percentage of variation that each principal coordinate accounts for.
Another way to calculate the percent variation is to look at the `Relative_eig` column.

```{r axis-percent}
# Dimension (i.e., Axis 1 (PCOA1))
Axis1.percent <-
  princoor.pathotype$values$Relative_eig[[1]] * 100

# Dimension (i.e., Axis 2 (PCOA2))
Axis2.percent <-
  princoor.pathotype$values$Relative_eig[[2]] * 100

Axis1.percent

Axis2.percent
```

Now we can make a data frame with the two principal coordinates that account for the most variation in the data.
We will then add metadata to the data frame `pca.data`.

```{r create-df}
princoor.pathotype.data <-
  data.frame(
    Sample = as.integer(rownames(princoor.pathotype$vectors)),
    X = princoor.pathotype$vectors[, 1],
    Y = princoor.pathotype$vectors[, 2]
  )
```

# Add Metadata to your PCOA Data

You will need to add information on the sample collection location or other data to help identify different pathotype groupings based on geographic location or other factors.
We will use `left_join()` from {dplyr} to combine the `princoor.pathotype.data` with the metadata that we've already loaded, `sample_meta` that contains a geographic location (state name).

```{r merge-metadata}
princoor.pathotype.data <-
  left_join(princoor.pathotype.data, sample_meta, by = "Sample")

princoor.pathotype.data
```

Now we will plot the PCA data using {ggplot2} and color the points based on location, `Locale`, and identify the 95% confidence interval of those groups using the `stat_ellipse()` function.

```{r ggplot-pca}
ggplot(data = princoor.pathotype.data, aes(x = X, y = Y)) +
  geom_point(aes(colour = Locale)) +
  xlab(paste("PCOA1 - ", round(Axis1.percent, 2), "%", sep = "")) +
  ylab(paste("PCOA2 - ", round(Axis2.percent, 2), "%", sep = "")) +
  theme_bw() +
  theme(
    axis.title.x = element_text(face = "bold", size = 15),
    axis.title.y = element_text(face = "bold", size = 15),
    axis.text = element_text(face = "bold", size = 10),
    legend.title = element_text(face = "bold", size = 10),
    legend.text = element_text(face = "bold", size = 10),
    legend.key.size = unit(1, 'lines')
  ) +
  stat_ellipse(data = princoor.pathotype.data, aes(x = X, y = Y),
               level = 0.95) +
  ggtitle("Pathotype Jaccard Distances PCOA")
```

# Statistical Tests for Beta Diversity

When using two or more pathotype datasets for comparisons, you can use beta-diversity tests to identify if there are significant differences between their sampled pathotype compositions.
These code are presented as an example for further downstream analysis that can be used when comparing two or more populations' pathotype composition.

In these examples we will artificially split the dataset into two, so that these analyses can be shown.
When performing your own analyses you will likely have two geographic locations to compare already.
Make sure you can differentiate these populations with the metadata file used previously (*i.e.*, column in the dataset that specifies where the isolate came from; USA, Brazil, China, Australia, etc.).

# Permutation Based Analysis of Variance (PERMANOVA) and Beta-dispersion Analyses

## Beta-Dispersion

Beta-dispersion tests if the dispersion, variance, of two or more groups are significantly different or not.
First, an item named "groups" must be made that contains lists of the location and number of isolates from that location used in the analysis.
We will then check to make sure the lists in "groups" adds up to the number of isolated used in analysis.

First, make a list of the locations for each pathotype.
Note that when you are using two or more locations you will need to make a list for each location with a length of isolates used.

```{r create-group-lists}
groups <- factor(c(rep("Michigan_1", 11), rep("Michigan_2", 10)))

# this number shows how many isolates are in all "groups" lists combined
length(groups)

# this shows the number of isolates within your data set, these numbers should
# match for downstream analyses to work!! 
length(unique(P_sojae_survey$Isolate))
```

Next, beta-dispersion will be calculated using the Jaccard distance matrix made previously.
An ANOVA is then performed to identify significance within the dataset.
Post-hoc tests can be used to identify significant interactions between specific locations within the dataset.
This can then be plotted to visualize how the beta-dispersion is different between groups.

```{r beta-dispersion}
 # calculates the beta-dispersion for each group, when comparing 2 or more
pathotype.disp <-
  betadisper(P_sojae_survey.matrix.jaccard, groups)

# tests if centroid distances are significantly different from each other
pathotype.disp.anova <- anova(pathotype.disp) 
pathotype.disp.anova

# test significance between each group
pathotype.disp.TukeyHSD <- TukeyHSD(pathotype.disp)
pathotype.disp.TukeyHSD

# plot showing the dispersion for each group
plot(pathotype.disp, hull = FALSE, ellipse = TRUE)
```

The ANOVA identified no significant differences between groups dispersion (p = `r pathotype.disp.TukeyHSD$group[4]`).
This means that the groups dispersion, or variance, is not significantly different from each other and the groups dispersion is likely homogeneous between groups.
At this point, a Tukey HSD test is not warranted, but we use it as an example here.
Again, a p-value of `r pathotype.disp.TukeyHSD$group[4]` is reported from the Tukey HSD tests and we reject the hypothesis that these groups may have different dispersion.
We can plot the dispersion for each group using the `plot()` function.
As expected, since we have identified no significant differences, the two groups dispersion overlap a great deal and are not distinct from each other.
Again this shows that pathotype dispersion between the groups is homogeneous and not different in this instance.

If we were working with a data set that had groups with significantly different dispersion we would expect to see a significant ANOVA p-value (p \< 0.05) as well as significance when using the Tukey HSD test.
Lastly, the plotted dispersion will form distinct, separate, groups which can be observed.

Differences in beta-dispersion may indicate separate pathotype groups which should be further investigated with Permutation Based Analysis of Variance (PERMANOVA) and Analysis of Similarity (ANOSIM) analysis.
Groups which have similar dispersion may still be significantly different in regards to their centroids, which will be tested using a PERMANOVA.

## Permutation Based Analysis of Variance (PERMANOVA)

PERMANOVA tests if the centroids, similar to means, of each group are significantly different from each other.
Likewise, an $R^2$ statistic is calculated, showing the percentage of the variance explained by the groups.

```{r adonis}
pathotype.adonis <- adonis2(P_sojae_survey.matrix.jaccard ~ groups)

pathotype.adonis
```

The PERMANOVA identified no significant differences between the groups centroids, or means (*p* = `r pathotype.adonis[[5]][[1]]`).
In addition to identifying significance between group centroids, the PERMANOVA also calculates how much of the variance can be explained by the specified groups (see the $R^2$ column in the PERMANOVA output).
In this case, the $R^2$ is `r pathotype.adonis[[3]][[1]]`, so `r round(pathotype.adonis[[3]][[1]], 3) * 100`% of the variance is explained by the groups used in analysis.
Based on the PERMANOVA results we can conclude that these two groups are not different from each other and likely have similar pathotypes to each other.

## Analysis of Similarity (ANOSIM)

ANOSIM statistic (R) ranges from between -1 and 1.
Positive numbers suggest that there is more similarity within groups than there is between groups.
Values close to zero indicate no difference between groups (*i.e.*, similarities are the same between groups).

```{r anosim}
pathotype.anosim <- anosim(P_sojae_survey.matrix.jaccard, groups)

pathotype.anosim
```

ANOSIM statistic (R) was `r pathotype.anosim$statistic`, so there are more similarities between groups than there are within groups.
This is evidence that the groups are not different from one another.
Likewise the significance is \>0.05 so there is no significant difference between groups' similarities.
