# Purpose of this analysis

This notebook takes data and metadata from refine.bio and identifies differentially expressed genes.

⬇️ [**Jump to the analysis code**](#analysis) ⬇️

# How to run this example

For general information about our tutorials and the basic software packages you will need, please see our ['Getting Started' section](https://alexslemonade.github.io/refinebio-examples/01-getting-started/getting-started.html#how-this-tutorial-is-structured).
We recommend taking a look at our [Resources for Learning R](https://alexslemonade.github.io/refinebio-examples/01-getting-started/getting-started.html#resources-for-learning-r) if you have not written code in R before.

## Obtain the `.Rmd` file

To run this example yourself, [download the `.Rmd` for this analysis by clicking this link](https://alexslemonade.github.io/refinebio-examples/02-microarray/differential-expression_microarray_01_2-groups.Rmd).

Clicking this link will most likely send this to your downloads folder on your computer.
Move this `.Rmd` file to where you would like this example and its files to be stored.

You can open this `.Rmd` file in RStudio and follow the rest of these steps from there. (See our [section about getting started with R notebooks](https://alexslemonade.github.io/refinebio-examples/01-getting-started/getting-started.html#how-to-get-and-use-rmds) if you are unfamiliar with `.Rmd` files.)

## Set up your analysis folders

Good file organization is helpful for keeping your data analysis project on track!
We have set up some code that will automatically set up a folder structure for you.
Run this next chunk to set up your folders!

If you have trouble running this chunk, see our [introduction to using `.Rmd`s](https://alexslemonade.github.io/refinebio-examples/01-getting-started/getting-started.html#how-to-get-and-use-rmds) for more resources and explanations.

```{r}
# Create the data folder if it doesn't exist
if (!dir.exists("data")) {
  dir.create("data")
}

# Define the file path to the plots directory
plots_dir <- "plots"

# Create the plots folder if it doesn't exist
if (!dir.exists(plots_dir)) {
  dir.create(plots_dir)
}

# Define the file path to the results directory
results_dir <- "results"

# Create the results folder if it doesn't exist
if (!dir.exists(results_dir)) {
  dir.create(results_dir)
}
```

In the same place you put this `.Rmd` file, you should now have three new empty folders called `data`, `plots`, and `results`!

## Obtain the dataset from refine.bio

For general information about downloading data for these examples, see our ['Getting Started' section](https://alexslemonade.github.io/refinebio-examples/01-getting-started/getting-started.html#how-to-get-the-data).

Go to this [dataset's page on refine.bio](https://www.refine.bio/experiments/GSE71270/creb-overexpression-induces-leukemia-in-zebrafish-by-blocking-myeloid-differentiation-process).

Click the "Download Now" button on the right side of this screen.  

<img src="https://github.com/AlexsLemonade/refinebio-examples/raw/40e47f4d3f39283effbd9843a457168061be9680/template/screenshots/download-now.png" width=200>  

Fill out the pop up window with your email and our Terms and Conditions:  

<img src="https://github.com/AlexsLemonade/refinebio-examples/raw/40e47f4d3f39283effbd9843a457168061be9680/template/screenshots/download-email.png" width=500>  

It may take a few minutes for the dataset to process.
You will get an email when it is ready.

## About the dataset we are using for this example

For this example analysis, we will use this [zebrafish gene expression dataset](https://www.refine.bio/experiments/GSE71270/creb-overexpression-induces-leukemia-in-zebrafish-by-blocking-myeloid-differentiation-process).
@Tregnago2016 used microarrays to measure gene expression of ten zebrafish samples, five overexpressing human CREB, as well as five control samples.
In this analysis, we will test differential expression between the control and CREB-overexpressing groups.

## Place the dataset in your new `data/` folder

refine.bio will send you a download button in the email when it is ready.
Follow the prompt to download a zip file that has a name with a series of letters and numbers and ends in `.zip`.
Double clicking should unzip this for you and create a folder of the same name.  

<img src="https://github.com/AlexsLemonade/refinebio-examples/raw/40e47f4d3f39283effbd9843a457168061be9680/template/screenshots/download-folder-structure.png" width=400>

For more details on the contents of this folder see [these docs on refine.bio](http://docs.refine.bio/en/latest/main_text.html#downloadable-files).  

The `<experiment_accession_id>` folder has the data and metadata TSV files you will need for this example analysis.
Experiment accession ids usually look something like `GSE1235` or `SRP12345`.

Copy and paste the `GSE71270` folder into your newly created `data/` folder.

## Check out our file structure!

Your new analysis folder should contain:

- The example analysis `.Rmd` you downloaded  
- A folder called "data" which contains:
  - The `GSE71270` folder which contains:
    - The gene expression  
    - The metadata TSV  
- A folder for `plots` (currently empty)  
- A folder for `results` (currently empty)  

Your example analysis folder should now look something like this (except with respective experiment accession ID and analysis notebook name you are using):

<img src="https://github.com/AlexsLemonade/refinebio-examples/raw/40e47f4d3f39283effbd9843a457168061be9680/template/screenshots/analysis-folder-structure.png" width=400>

In order for our example here to run without a hitch, we need these files to be in these locations so we've constructed a test to check before we get started with the analysis.
These chunks will declare your file paths and double check that your files are in the right place.

First we will declare our file paths to our data and metadata files, which should be in our data directory.
This is handy to do because if we want to switch the dataset (see next section for more on this) we are using for this analysis, we will only have to change the file path here to get started. 

```{r}
# Define the file path to the data directory
# Replace with the path of the folder the files will be in
data_dir <- file.path("data", "GSE71270")

# Declare the file path to the gene expression matrix file
# inside directory saved as `data_dir`
# Replace with the path to your dataset file
data_file <- file.path(data_dir, "GSE71270.tsv")

# Declare the file path to the metadata file
# inside the directory saved as `data_dir`
# Replace with the path to your metadata file
metadata_file <- file.path(data_dir, "metadata_GSE71270.tsv")
```

Now that our file paths are declared, we can use the `file.exists()` function to check that the files are where we specified above. 

```{r}
# Check if the gene expression matrix file is at the path stored in `data_file`
file.exists(data_file)

# Check if the metadata file is at the file path stored in `metadata_file`
file.exists(metadata_file)
```

If the chunk above printed out `FALSE` to either of those tests, you won't be able to run this analysis _as is_ until those files are in the appropriate place.

If the concept of a "file path" is unfamiliar to you; we recommend taking a look at our [section about file paths](https://alexslemonade.github.io/refinebio-examples/01-getting-started/getting-started.html#an-important-note-about-file-paths-and-Rmds).

# Using a different refine.bio dataset with this analysis?

If you'd like to adapt an example analysis to use a different dataset from [refine.bio](https://www.refine.bio/), we recommend placing the files in the `data/` directory you created and changing the filenames and paths in the notebook to match these files (we've put comments to signify where you would need to change the code).
We suggest saving plots and results to `plots/` and `results/` directories, respectively, as these are automatically created by the notebook.
From here you can customize this analysis example to fit your own scientific questions and preferences.

***

<!-- Do not delete this line --> <a name="analysis" style="padding-top:56px;margin-top:-56px;">&nbsp;</a>

# Differential Expression - Microarray

## Install libraries

See our Getting Started page with [instructions for package installation](https://alexslemonade.github.io/refinebio-examples/01-getting-started/getting-started.html#what-you-need-to-install) for a list of the other software you will need, as well as more tips and resources.

In this analysis, we will be using `limma` for differential expression [@Ritchie2015].
We will also use `EnhancedVolcano` for plotting [@Blighe2020].

```{r}
if (!("limma" %in% installed.packages())) {
  # Install this package if it isn't installed yet
  BiocManager::install("limma", update = FALSE)
}
if (!("EnhancedVolcano" %in% installed.packages())) {
  # Install this package if it isn't installed yet
  BiocManager::install("EnhancedVolcano", update = FALSE)
}
```

Attach the packages we need for this analysis.

```{r message=FALSE}
# Attach the library
library(limma)

# We will need this so we can use the pipe: %>%
library(magrittr)

# We'll use this for plotting
library(ggplot2)
```

The jitter plot we make later on with `geom_jitter()` involves some randomness. 
As is good practice when our analysis involves randomness, we will set the seed.
<!-- TODO: link to glossary about setting the seed -->

```{r}
set.seed(12345)
```

## Import and set up data

Data downloaded from refine.bio include a metadata tab separated values (TSV) file and a data TSV file.
This chunk of code will read the both TSV files and add them as data frames to your environment.

We stored our file paths as objects named `metadata_file` and `data_file` in [this previous step](#check-out-our-file-structure).

```{r}
# Read in metadata TSV file
metadata <- readr::read_tsv(metadata_file)

# Read in data TSV file
expression_df <- readr::read_tsv(data_file) %>%
  # Tuck away the Gene ID column as row names
  tibble::column_to_rownames("Gene")
```

Let's ensure that the metadata and data are in the same sample order.

```{r}
# Make the data in the order of the metadata
expression_df <- expression_df %>%
  dplyr::select(metadata$geo_accession)

# Check if this is in the same order
all.equal(colnames(df), metadata$geo_accession)
```

## Set up design matrix

`limma` needs a numeric design matrix to signify which are CREB and control samples.
Here we are using the treatments described in the metadata table in the `genotype/variation` column to create a design matrix where the "control" samples are assigned `0` and the "overexpressing the human CREB" samples are assigned `1`.
Note that the metadata columns that signify the treatment groups might be different across datasets, and will almost certainly have different contents.

While the `genotype/variation` column contains the group information we will be using for differential expression, the `/` it contains in its column name makes it more annoying to access.  
Accessing variable that have names with special characters like `/`, or spaces, require extra work-arounds to ignore R's normal interpretations of these characters.
Here we will rename it as just `genotype` to make our lives later much easier.

We will also recode the contents of the column, as `overexpressing the human CREB"` is a bit of an unruly name. 
To do this, we will use the `fct_recode()` function from the `forcats` package, simplifying `"overexpressing the human CREB"` to just `CREB`.
We will also use `fct_relevel()` to make sure our `control` samples appear first in the factor levels.


```{r}
# These renaming steps will not be the same (or might not be needed at all)
# with a different dataset
metadata <- metadata %>%
  # rename the column
  dplyr::rename("genotype" = `genotype/variation`) %>%
  # change the names and order of the genotypes (making the column a factor)
  dplyr::mutate(
    genotype = genotype %>%
      # rename the "overexpressing..." genotype to "CREB"
      forcats::fct_recode(CREB = "overexpressing the human CREB") %>%
      # make "control" the first level of the factor
      forcats::fct_relevel("control")
  )
```

Now we will create a model matrix based on our newly renamed `genotype` variable.

```{r}
# Create the design matrix from the genotype information
des_mat <- model.matrix(~genotype, data = metadata)

# Look at the design matrix
head(des_mat)
```

When we look at this design matrix, we see that there is now a `genotypeCREB` column that defines the group for each sample: 0 for control samples and 1 for the CREB samples. 
(The model will also fit an intercept for all samples, so we can see that here as well.)

## Perform differential expression

We will use the `lmFit()` function from the `limma` package to test each gene for differential expression between the two groups using a linear model.
After fitting our data to the linear model, in this example we apply empirical Bayes smoothing with the `eBayes()` function.

Here's a [nifty article and example](http://varianceexplained.org/r/empirical_bayes_baseball/) about what the empirical Bayes smoothing is for [@bayes-estimates].

```{r}
# Apply linear model to data
fit <- lmFit(expression_df, design = des_mat)

# Apply empirical Bayes to smooth standard errors
fit <- eBayes(fit)
```

Because we are testing many different genes at once, we also want to perform some multiple test corrections, which we will do with the Benjamini-Hochberg method while making a table of results with `topTable()`.
The `topTable()` function default is to use Benjamini-Hochberg but this can be changed to a different method using the `adjust.method` argument (see the `?topTable` help page for more about the options).

```{r}
# Apply multiple testing correction and obtain stats
stats_df <- topTable(fit, number = nrow(expression_df)) %>%
  tibble::rownames_to_column("Gene")
```

Let's take a peek at our results table.

```{r rownames.print = FALSE}
head(stats_df)
```

By default, results are ordered by largest `B` (the log odds value) to the smallest, which means your most differentially expressed genes should be toward the top.

See the help page by using `?topTable` for more information and options for this table.

## Check results by plotting one gene

To test if these results make sense, we can make a plot of one of top genes.
Let's try extracting the data for `ENSDARG00000104315` and set up its own data frame for plotting purposes.

```{r}
top_gene_df <- expression_df %>%
  # Extract this gene from `expression_df`
  dplyr::filter(rownames(.) == "ENSDARG00000104315") %>%
  # Transpose so the gene is a column
  t() %>%
  # Transpose made this a matrix, let's make it back into a data frame
  data.frame() %>%
  # Store the sample ids as their own column instead of as row names
  tibble::rownames_to_column("refinebio_accession_code") %>%
  # Join on the selected columns from metadata
  dplyr::inner_join(dplyr::select(
    metadata,
    refinebio_accession_code,
    genotype
  ))
```

Let's take a sneak peek at what our `top_gene_df` looks like.

```{r}
top_gene_df
```

Now let's plot the data for `ENSDARG00000104315` using our `top_gene_df`.

```{r}
ggplot(top_gene_df, aes(x = genotype, y = ENSDARG00000104315, color = genotype)) +
  geom_jitter(width = 0.2, height = 0) + # We'll make this a jitter plot
  theme_classic() # This makes some aesthetic changes
```

These results make sense.
The overexpressing CREB group samples have much higher expression values for ENSDARG00000104315 than the control samples do.

## Write results to file

The results in `stats_df` will be saved to our `results/` directory.

```{r}
readr::write_tsv(stats_df, file.path(
  results_dir,
  "GSE71270_limma_results.tsv" # Replace with a relevant output name
))
```

## Make a volcano plot

We'll use the `EnhancedVolcano` package's main function to plot our data [@Zhu2018].

```{r}
EnhancedVolcano::EnhancedVolcano(stats_df,
  lab = stats_df$Gene, # This has to be a vector with our labels we want for our genes
  x = "logFC", # This is the column name in `stats_df` that contains what we want on the x axis
  y = "adj.P.Val" # This is the column name in `stats_df` that contains what we want on the y axis
)
```

In this plot, green points represent genes that meet the log2 fold change, by default the cutoff is absolute value of 1.  
But there are no genes that meet the p value cutoff, which by default is `1e-05`.
We used the adjusted p values for our plot above, so you may want to adjust this with the `pCutoff` argument (Take a look at all the options for tailoring this plot using `?EnhancedVolcano`).

Let's make the same plot again, but adjust the `pCutoff` since we are using multiple-testing corrected p values, and this time we will assign the plot to our environment as `volcano_plot`.

```{r}
volcano_plot <- EnhancedVolcano::EnhancedVolcano(stats_df,
  lab = stats_df$Gene,
  x = "logFC",
  y = "adj.P.Val",
  pCutoff = 0.01 # Because we are using adjusted p values, we can loosen this a bit
)

# Print out our plot
volcano_plot
```

Let's save this plot to a PNG file.

```{r}
ggsave(
  plot = volcano_plot,
  file.path(plots_dir, "GSE71270_volcano_plot.png")
) # Replace with a plot name relevant to your data
```

# Resources for further learning

- [The refine.bio example for differential expression with more than 2 groups](https://alexslemonade.github.io/refinebio-examples/02-microarray/differential-expression_microarray_02_several-groups.html)
- [The full users guide on limma](https://bioconductor.org/packages/release/bioc/vignettes/limma/inst/doc/usersguide.pdf) shows examples of limma functions for different experimental models [@Ritchie2015].
- [A general guide to differential expression, including a section about interpreting results](http://www.nathalievialaneix.eu/doc/pdf/tutorial-rnaseq.pdf) [@Gonzalez2014].
- [End to End workflow for Affymetrix microarray data](https://www.bioconductor.org/packages/devel/workflows/vignettes/maEndToEnd/inst/doc/MA-Workflow.html) [@Klaus2018].
- [The `EnhancedVolcano` vignette](https://www.bioconductor.org/packages/release/bioc/vignettes/EnhancedVolcano/inst/doc/EnhancedVolcano.html) has more examples on how to tailor your volcano plot [@Blighe2020].

# Session info

At the end of every analysis, before saving your notebook, we recommend printing out your session info.
This helps make your code more reproducible by recording what versions of software and packages you used to run this.

```{r}
# Print session info
sessioninfo::session_info()
```

# References
