---
title: "**Bioinformatic Analysis of RNA-sequencing** <br> <br> R Introduction: Variables"
subtitle: "Allison Burns, Maxime Jan, Linda Mhalla, Christian Iseli, Nicolas Guex"
output:
  ioslides_presentation:
    css: ../css/styles.css
    incremental: no
    widescreen: true
    toc: yes
    transition: faster
---


```{r,echo=F,warning=F,message=F}
if (!require("ggplot2")) install.packages("ggplot2")
```



# General R guidelines

## Packages {.pre}

To install a package available in [CRAN](https://cran.r-project.org/web/packages/available_packages_by_name.html)

```{r,eval=F}
install.packages("ggplot2")
```

load the package using: 

```{r,message=F,warning=F}
library(ggplot2) # Load
detach(package:ggplot2,unload=T) # Unload
```


Other packages like DESeq2 are only available in [Bioconductor](https://bioconductor.org/packages/release/bioc/)

you can install them like this:

```{r,eval=F}
if (!require("BiocManager", quietly = TRUE))
    install.packages("BiocManager")

BiocManager::install("DESeq2")
```

If two package have the same function name use the format *Package::Function*, (e.g. above *BiocManager::install("DESeq2")*)

If you want to know where your packages are, run this command:

```{r,eval=F}
.libPaths()
```

## Help

You can see the help of a function using "?"

```{r,eval=F}
?write.table
```

```{r, echo=FALSE, out.width="75%"}
knitr::include_graphics("image/help.PNG")
```


## Working directory {.pre}

Always think where is your "working directory (wd)" in R

In an Rmd, the working directory is located in the same directory as the Rmd file

```{r}
# Get the working directory
getwd()
```

You can change the working directory, but it will be only valid for a chunk

```{r}
setwd(dir = "image/")
list.files(path=".")
```

if you want to change the wd for all the document:

```{r}
# knitr::opts_knit$set(root.dir = '/tmp')
```


## Comments {.pre}

You can use comment in your code or Rmarkdown chunk using the # character


```{r}
# This is a comment
1 + 1 
```

## Variable name {.pre}

Some variable name should not be used:

```{r}
# Legal variable names:
myvar <- "John"
my_var <- "John"
myVar <- "John"
MYVAR <- "John"
myvar2 <- "John"
.myvar <- "John"
```
```{r,eval=F}
# Illegal variable names:
2myvar <- "John"
my-var <- "John"
my var <- "John"
_my_var <- "John"
my_v@ar <- "John"
TRUE <- "John"
```



# Variables in R

## Numeric variables {.pre}

Attribute value to a variable (<span style="color: red;">R is case sensitive !</span>)

```{r}
# Single variable
MyVariable<-15
# Vector 
ManyVariables<-c(1,2,3,4,5)
```


:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}

<ins>
**Integer**
  
</ins>

```{r}
# Add L to force number to be integer
SomeNumbers<-c(1L,22L,185L)
SomeNumbers
```

```{r}
class(SomeNumbers)
```


:::
::: {}

<ins>
**Double**

</ins>

```{r}
SomeDoubleNumbers<-c(1.21, 2/3 , pi)
SomeDoubleNumbers
```

```{r}
class(SomeDoubleNumbers)
```

:::
::::


## Boolean variables {.pre}

Variables are only TRUE or FALSE (<span style="color: red;">Do not use quotes !</span>)

```{r}
MyBoolean<-c(TRUE,FALSE,TRUE,FALSE)
MyOtherBoolean<-c(TRUE,TRUE,FALSE,FALSE)
```

Some operation that return boolean:

:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}

<ins>
**AND**

</ins>

```{r}
MyBoolean & MyOtherBoolean
```

<ins>
**OR**

</ins>

```{r}
MyBoolean | MyOtherBoolean
```

:::
::: {}

<ins>
**NOT**

</ins>

```{r}
!MyBoolean
```

<ins>
**Compare values**

</ins>


```{r}
SomeDoubleNumbers<-c(1.21, 2/3 , pi)
SomeNumbers<-c(1L,1L,1L)
SomeDoubleNumbers > SomeNumbers
```


:::
::::



## Characters & Factors {.pre}

:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}

Often these two data types are confunded

```{r}
Condition<-c("Ctr","Ctr","Treat","Treat")
Condition_AsFactor<-factor(Condition)
```

<ins>
**Character**

</ins>

```{r}
# print character
Condition
class(Condition)
class(Condition_AsFactor)
```

:::
::: {}

<ins>
**Factor**

</ins>

```{r}
# print factors
Condition_AsFactor
# At a lower level, factors are stored as integer
typeof(Condition_AsFactor)
```

You can get the levels of a factor

```{r}
levels(Condition_AsFactor)
```


:::
::::


## Vectors {.pre}

:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}


You can only have **one** type of variable in a vector. 

```{r}
# Here numeric values are converted into characters
MyVectory<-c("A",1.2,2/4,2L)
MyVectory
```

To access a value in a vector use brackets "[]" (e.g. MyVectory[1])

You can access multiple elements

```{r}
MyVectory[1:3]
# To access the last element of a vector: 
# MyVectory[length(MyVectory)] or tail(MyVectory,1)
```

:::
::: {}

Vectors can be named (often required in packages)

```{r}
MyGenes<-c("Arntl"=1.5,"Per2"=1.8,"Cdk4"=8.5)
MyGenes
```

You can change the names of the vectors

```{r}
names(MyGenes)
# Change name 2
names(MyGenes)[2]<-"Cry1"
MyGenes
```


:::
::::


## Lists {.pre}

If you want multiple type of variable, you can use lists.

<span style="color: green;">You don't need same length for each element in the list</span>


```{r}
MyList<-list("SomeNumber"=c(1.5,2.3,4.5),
             "SomeName"=c("Gene1","Gene2","Gene3","Gene4","Gene5"),
             "SomeFactors"=factor(c("C1","C1","C2","C4")))
```

:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}

You can see the names of elements in the list

```{r}
names(MyList)
```


You can access the "Numbers" of the list using brackets

<span style="color: red;">But, it will return a list of 1 element </span>

```{r}
MyList["SomeNumber"]
```

:::
::: {}

To access the vector use double brackets or $

```{r}
MyList$SomeNumber
MyList[["SomeNumber"]]
```

:::
::::


## Matrix {.pre}

:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}

Matrix contains only **one** type of variable

```{r}
# Completion is done by column
MyMatrix<-matrix(c(1,2,3,4,5,6),ncol=2)
```

```{r}
MyMatrix
```

You can change rownames and colnames

```{r}
colnames(MyMatrix)<-c("A","B")
rownames(MyMatrix)<-c("C","D","E")
```



:::
::: {}

You can acces a specific column or row

<span style="color: red;">If only 1 row/column is requested, R return a vector. Think to use ,drop=F !</span>

```{r}
MyMatrix[1,] # First row
```

```{r}
MyMatrix[,1] # First column
```

- MyMatrix[,1] will return a vector
- MyMatrix[,1,drop=F] will return a 2-dimension item
- MyMatrix[,1:2] will return a 2-dimension item

:::
::::

## Data.frame {.pre}

Similar to matrix, but can contain multiple type of data 

`r set.seed(12)`

```{r}
MyDataFrame<-data.frame("Read_counts"=rpois(4,lambda = 4),
                        "Genes"=c("Cry1","Per2","Arntl","Cdk4"))
MyDataFrame
```


<span style="color: red;">Again, be carefull to variable type conversion when selecting a single item !</span>

:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}

Selecting 1 row kept the data.frame format

```{r}
class(MyDataFrame[1,])
```

:::
::: {}

but not when selecting 1 column

```{r}
# Same if you use class( MyDataFrame$Read_counts )
class(MyDataFrame[,1])
```
  
:::
::::

## cbind and rbind {.pre}

You may want to add new data to your data.frame or matrix, you can use rbind to add new line or cbind to add new row.


```{r}
MyDataFrame
```

:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}

```{r}
MyDataFrame<-cbind(MyDataFrame,PassQC=c(T,F,F,T))
MyDataFrame
```

:::
::: {}

```{r}
MyDataFrame<-rbind(MyDataFrame,list(3,"P53",T))
MyDataFrame
```

:::
::::


## Indexing {.pre}

:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}

To acces certain information, you can in use logical indexing. e.g. filter low count reads:

```{r}
MyDataFrame
```

Here we keep only gene with a minimum of 3 counts

```{r}
MyDataFrame[MyDataFrame$Read_counts > 3,]
```


:::
::: {}

You can see the logical index that was given

```{r}
MyDataFrame$Read_counts > 3
```

This is equivalient to give:

```{r}
MyDataFrame[c(FALSE,TRUE,TRUE,FALSE),]
```

Some operator

- ">" more than
- "<" less than
- "==" equal (but see which)
- "!=" not equal
  
:::
::::

## Which functions {.pre}

:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}


The standard operator can be sometime problematic with NA

```{r}
MyGenes<-c("Arntl"=1.5,"Per2"=1.8,"Cdk4"=8.5,"Cry1"=NA)
MyGenes
```

it will return NA value

```{r}
MyGenes[MyGenes>2]
```


:::
::: {}

you can easily use which

```{r}
MyGenes[which(MyGenes>2)]
```

it return the an index which are TRUE 

```{r}
which(MyGenes>2)
```

you can also use it for min or max value

- which.min(MyGenes)
- which.max(MyGenes)


:::
::::

## The %in% operator {.pre}

You can return index for item that match multiple requirement


```{r}
MyGenes<-c("Arntl"=1.5,"Per2"=1.8,"Cdk4"=8.5,"Cry1"=NA)
MyGenesName<-names(MyGenes)
```

Find the names equal to Arntl and Per2

```{r}
idx<-MyGenesName %in% c("Arntl","Per2")
MyGenesName[idx]
```

or genes with specific values

```{r}
idx<-MyGenes %in% c(1.5,8.5)
MyGenesName[idx]
```

## Remove item in list {.pre}

You can remove some item by using the '-' sign

```{r}
MyGenes<-c("Arntl"=1.5,"Per2"=1.8,"Cdk4"=8.5,"Cry1"=NA)
```

Remove genes with value < 1.8

```{r}
MyGenes[-which(MyGenes<1.8)]
```

also remove NA 

```{r}
# less than 1.8 OR value equal NA
MyGenes[-which(MyGenes<1.8 | is.na(MyGenes))]
```


## Transform data {.pre}

```{r}
as.numeric(c("1","2","3"))
```

```{r}
as.character(22:25)
```


# Exercice 2








