---
title: 'Reorganisation following disturbance: multi trait-based methods in R'
authors: "Laura Richardson, Camille Magneville, Laura Grange, Jenny Shepperson, Martin Skov, Andrew Hoey, Adel Heenan"
output:
  word_document: default
  pdf_document: default
  html_notebook: default
---

# Practical  preparation

We will run this practical in R. If you have used R before great, if you have and it was a little while ago no problem, the practical instructions will walk you through step by step. 

For this practical we will be using a cloud-based version of RStudio as this will avoid R version control issues.

Before coming to the practical you need to follow the instructions below, so you are ready to work on the assignment from the start of the practical session. The steps are relatively straight forward, but depending on internet connection can take about 20 minutes to get set up and install the R packages required, so be sure to do this before the timetabled practical session.

Before the first practical session you should also read the practical introduction document and the key reading – to familiarise yourself with the topics we will cover. 


# Accessing the data and working in Rstudio cloud

First of all, you will need to get the datafile for Part 1 - called LI_fish_abundance_pre_post_bleaching.csv. Download the datafile to your computer. Next you will have to log onto Rstudio (use either the university server version or free version of RStudio cloud). 

Rstudio is the interface through which we will use R which is the programming environment. 

1.	Log onto RStudio

2.  Create a new project and name it Trait-based_diversity_practical

3.	Upload the datafile (LI_fish_abundance_pre_post_bleaching.csv) into R by clicking the Upload button in the bottom right pane


![The RStudio interface*](images/interface_upload.png)

4.	Navigate to the directory where you downloaded and saved the data file, click on file (the file name is LI_fish_abundance_pre_post_bleaching.csv) and click open, then OK.

5.	You will see that the file is now loaded onto your Rstudio workspace in the cloud

6.	Next click on File / New file / R Script

7.	A new window will open on the top left, this is your script. First thing to do is save it, by clicking on the save icon at the top of the window. Save it as Day_1_code.R

![The RStudio interface*](images/interface_save.png)

An alternative approach to uploading the data using steps 3 and 4 above, is to open and save a new R script (steps 6 and 7 above), and then use the function setwd() to tell R which folder on your computer to source data files from, i.e., 'setting your working directory'. Either option is fine. 

To set your working directory, type the following line into your script with the full filepath name where you have saved your datafiles (top left). For example, 'C:/Documents/Trait-based_diversity_practical/R'. Pass it to R (as described here below in ## Loading the data into the R environment):
```{r, eval=  FALSE}

setwd("C:/Documents/Trait-based_diversity_practical/R") # NB. Exchange this filepath for your own
```
<br>
<br>
<br>

## Understanding the RStudio interface

R is the programming environment. In its simplest form R is a fancy calculator and it will do exactly what you tell it to do to. Like pressing buttons on a calculator if you make a mistake, it will return an error. When using R you have to pay extra attention to detail and check that you are typing and instructing R in the correct way. 

RStudio is the interface through which we will run R. There are 4 main sections in RStudio view:

![The RStudio interface*](images/interface_panes.png)

<br>
<br>
<br>


## Loading the data into the R environment

The data are currently in your working directory, or workspace. To use it in R, you need to load it into the R environment. You can do this by directly clicking on the datafile named LI_fish_abundance_pre_post_bleaching.csv in the bottom right pane or by writing the code in your script and passing it to the R console.

When you want to pass an instruction from the script to R you can do this by:

1.	Making sure the cursor is on the line of the script you want to run

2.	Pressing control and enter at the same time

3.	If you want to pass more than one line at once, you can highlight the lines then press and control enter

This passes the code from the script and runs it in the R console. Let’s try.

Type the following line into your script (top left). Pass it to R as described above. This will load the fish survey datafile into R:
```{r, eval=  FALSE}

dat<-read.csv("LI_fish_abundance_pre_post_bleaching.csv")
```

This command tells R to read in the csv file.

NOTE: in the practical handouts there will be chunks of code. You should either copy and paste this code into your script or type it out. I recommend typing it out, as it will be good practice for learning to pay attention to detail when coding.

You have created an object in R called dat, you did this by applying the function read.csv. A function in R is always followed by (). A function is simply a group of instructions that takes inputs (what is inside the brackets), uses them to compute other values and returns a result into the R environment – in this case a dataframe called dat.

##  Loading the required packages

The main reason R is so popular is that there are thousands of user-written packages available, and like R itself are totally free. R packages (sometimes called libraries) store groups of related functions, so when you load a package, all those functions become available for you to use in your R environment. Some packages are loaded automatically when you start R, these are the base packages. You can check which packages are loaded by typing this:

```{r, eval = FALSE}
path.package() ## displays location where packages will be downloaded and saved
```

NOTE: the # in R is useful as R will ignore anything past that symbol. You can annotate and make notes in your script using this symbol, as I have done above. This is good practice, as it will allow you to understand what you did and why, when you revisit the script in the future.

To save time and memory, R does not load all packages automatically. Some are available with the R install you have, you can load these with the `library()` function. 

Some require downloading from the web. Once these are downloaded (you only need to do this step once), then you can use the library function to load it.

For this practical, you will need to download some R packages for working with species count data and plotting the results. The following code will install the packages we will require for the practicals, and then load them to your R environment. The installation may take a few minutes (5-20 minutes depending on your internet connection) – don’t panic. In future you won’t have to install these – you will just load the libraries.

```{r, eval=FALSE}
# For data wrangling:
install.packages("reshape", dependencies=TRUE, repos='http://cran.rstudio.com/')
install.packages("tidyverse", dependencies=TRUE, repos='http://cran.rstudio.com/')

# For computing trait-based diversity (functional richness):
install.packages("mFD", dependencies=TRUE, repos='http://cran.rstudio.com/')

# For manually making a PCoA plot of fish species trait space
install.packages("vegan", dependencies=TRUE, repos='http://cran.rstudio.com/')
install.packages("ade4", dependencies=TRUE, repos='http://cran.rstudio.com/')
```

Pass this code from your script to the console (as described above). When installing these packages, R will return messages in the console on the installation process, while this is happening you can insert a ## in front of each of the install.package lines in your script, so R will ignore them in future. You will know all the packages are installed once the red stop symbol at the top of the R console goes away. You will also know it is done when you see the message: 

* DONE (packagename)

The downloaded source packages are in
	‘/tmp/RtmpQbk8Bx/downloaded_packages’
	
	
While you wait, you should read the 'Practical introduction' document.  There is some key reading listed at the bottom of that document. At a minimum, read the Introduction and Methods section to the Richardson et al. (2018) paper as you will need to refer to this to understand the dataset you will work with. Richardson et al. (2018) can be accessed free of charge and without subscription here: https://doi.org/10.25903/5b57c26b0beb7 (see Chapter 4). 

When you see that the packages have been installed, save your R script and close the RStudio browser tab.

Now you are ready for the practical – see you there! 


