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

# R workshop | Day 1 - beginner

## Why learn R? {.build}

- Free!
- Packages
- Community
  + [`#rstats`](https://twitter.com/search?q=%23rstats) on twitter
  + [rbloggers](http://www.r-bloggers.com/)
  + [stackoverflow](http://stackoverflow.com/questions/tagged/r) with a lot of tags like `dplyr`, `ggplot2` etc

```{r echo=FALSE, out.width='70%'}
knitr::include_graphics("http://lsru.github.io/r_workshop/img/r_community_500.png")
```

## Packages


<div class="columns-2">
- CRAN *<span class="green2">reliable: package is checked during submit process</span>*

```{r echo=FALSE, out.width='85%'}
knitr::include_graphics("http://lsru.github.io/r_workshop/img/install_packages_300.png")
```

- [GitHub](https://github.com/) using [devtools](https://github.com/hadley/devtools). *<span class="yellow2">Check [status](https://github.com/hadley/readr)</span>*

```{r, eval=FALSE}
# install.packages("devtools")
devtools::install_github("hadley/readr")
```

- [bioconductor](https://www.bioconductor.org/). *<span class="yellow2">Check [status](https://www.bioconductor.org/packages/release/bioc/html/limma.html)</span>*
```{r, eval=FALSE}
source("https://bioconductor.org/biocLite.R")
biocLite("limma")
```

```{r echo=FALSE, out.width='85%'}
knitr::include_graphics("http://lsru.github.io/r_workshop/img/install_console_200.png")
```


## More and more packages

![](img/packages_vs_r_version.jpg)

[source: Andrie de Vries](http://blog.revolutionanalytics.com/2016/04/cran-package-growth.html)

## Pipeline goal

[David Robinson](http://varianceexplained.org/) summarized the workflow on his laptop

<img src="img/drob_r_pipeline_600.jpg">

## Period of much suckiness

```{r, echo=FALSE}
#devtools::install_github("ijlyttle/vembedr")
library("vembedr")
suppressPackageStartupMessages(library("dplyr"))
embed_youtube("8SGif63VW6E", query = list(start = secs("4m12s")))
```

## Period of much suckiness

> Whenever you’re learning a new tool, for a long time you’re going to suck...</br>
> But the good news is that it's typical, that’s something that happens to everyone, and it’s only temporary.</br>
> -- <cite>[Hadley Wickham][1]</cite>

[1]:https://youtu.be/8SGif63VW6E?t=4m12s


# R data structures


## 1 dimension: atomic vector

_all elements of an `atomic vector` must be the same type_ [source](http://adv-r.had.co.nz/Data-structures.html#vectors)

concatenate elements of **same** type
```{r,collapse=TRUE}
x <- c(1, 1.24, "6")
x
is.vector(x)
x[1] # access 1st element
```


See if we enter 6 as **character**
```{r, collapse=TRUE}
x <- c(1, 1.24, "6")
x
is.vector(x)
is.list(x)
is.atomic(x)
```

## 1 dimension, lists

Lists are objects that could contain anything

```{r}
l <- list(a = 1:3, b = c("hello", "bye"), data = head(iris, 2))
is.vector(l)
is.list(l)
is.atomic(l)
l[1]
l[[1]]
# str(l)
```

## subsetting

vector
```{r, collapse=TRUE}
x
x[1]
x[-2] # return 1st and 3rd elements
x[c(1, 3)] # return 1st and 3rd elements
```

list
```{r, collapse=TRUE}
l[2]      # return a list
l[2][1]   # makes no sense
l[[2]]    # return a vector
l[[2]][1] # return 1st element, 2nd atomic vector
```

## factor


```{r, collapse=TRUE}
f <- rep(c("Male", "Female"), each = 4)
f
ff <- factor(f)
ff # levels are like dictionnary keys
str(ff) # structure of factor, integer behind
```
```{r, collapse=TRUE}
table(ff) # useful command to count entities
ff[3] <- "t" # error! "t" not in levels
```


## Accessing lists' elements {.smaller}

![](img/hadley_pepper.png)
![](img/hadley_pepper2.png)

## 2 dimensions: homogenous elements

`matrix`

```{r}
matrix(data = 1:6, nrow = 2, ncol = 3)
```


## 2 dimensions: data frames 

which are `lists` where all columns have **equal** length

```{r, collapse=TRUE}
class(iris)
class(unclass(iris))
```

Actually, better to use `tbl_df` _tibble diff_ [rstudio blog](https://blog.rstudio.org/2016/03/24/tibble-1-0-0/)

`data_frame()` does much less than `data.frame()`:

- never changes the type of the inputs (_e.g._ it never converts strings to factors!)
- never changes the names of variables
- never creates row.names()
- never print ALL rows

but display

- column types
- groups (`dplyr::group_by()`)


## subsetting data frames

data frame are lists
```{r, collapse=FALSE}
mtcars[[1]]
mtcars[["mpg"]]
```

but `$` is a shorthand for `[[`
```{r}
mtcars$mpg
```

# Rstudio | Integrated Development Editor

## Layout, 4 panels

<img src="img/rstudio_layout_850.png">

## Features

- Package management (including building)
- Console to run `R`, with syntax highligther
- Editor to work with scripts / markdown
- auto-completion using <kbd>TAB</kbd>
- Cheatsheets
- Keyboard shortcuts

<kbd>Cmd + Enter</kbd> (mac) or<kbd>Ctrl + Enter</kbd> (PC): sends the line or selection from the editor to the console and runs it.

<kbd>↑</kbd>: in the console browse previous commands

## Update options

Recommended in the [r4ds](http://r4ds.had.co.nz/introduction.html#prerequisites)
To get a clean environment at start-up

![](img/rstudio-workspace_500.png)

## Projects

Solve most issues with working directories, get rid of `setwd()`

![](img/rstudio_project.png)

# Chaining

## The pipe operator %>%

[magrittr by Stefan Milton Bache](https://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html)


<div class="columns-2">
Compare:
```{r}
set.seed(124)
x <- rnorm(10)
mean(x)
round(mean(x), 3)
```

with:
```{r}
set.seed(124)
rnorm(10) %>% mean %>% round(3)
```
<br><br><br><br><br>
</div>

## Easier to read

natural from left to right.

Even better with **one** instruction per line and **indentation**
```{r}
set.seed(124)
rnorm(10) %>%
  mean %>%
  round(3)
```

## placeholder = .

```{r, eval=FALSE}
x %>% f(.) 
#stands for (pipe to the 1st function argument)
f(x)
```

When not 1st argument
```{r}
sub("b", "B", letters[1:3])
letters[1:3] %>% sub("b", "B") # raises warning!
letters[1:3] %>% sub("b", "B", .)
```



# Tidying data | tidyr


## Definitions

+ **Variable**: A quantity, quality, or property that you can measure.
+ **Observation**: A set of values that display the relationship between variables. To be an observation, values need to be measured under similar conditions, usually measured on the same observational unit at the same time.
+ **Value**: The state of a variable that you observe when you measure it.

[source: Garret Grolemund](http://garrettgman.github.io/tidying/)

## Rules

1. Each variable is in its own column
2. Each observation is in its own row
3. Each value is in its own cell

```{r echo=FALSE, out.width='90%'}
knitr::include_graphics("http://lsru.github.io/r_workshop/img/tidy-1_600.png")
```

## Convert Long / wide format

The wide format is generally untidy _but_ found in the majority of datasets


```{r echo=FALSE, out.width='70%'}
knitr::include_graphics("http://lsru.github.io/r_workshop/img/tidy-gather_600.png")
```
```{r echo=FALSE, out.width='70%'}
knitr::include_graphics("http://lsru.github.io/r_workshop/img/tidy-spread_600.png")
```


## Demo with the iris dataset

```{r}
head(iris, 3)
```

gather

```{r}
library("tidyr")
iris_melt <- iris %>%
  tibble::rownames_to_column() %>%
  dplyr::tbl_df() %>%
  gather(flower, measure, contains("al"))
iris_melt
```

##

spread

```{r}
iris_melt %>%
  spread(flower, measure)
```

## Separate / Unite

```{r, echo=FALSE}
df <- data_frame(year = c(2015, 2014, 2014),
                 month = c(11, 2, 4),
                 day = c(23, 1, 30),
                 value = c("high", "low", "low"))
```

unite
```{r}
df %>%
  unite(date, c(year, month, day), sep = "-") -> df_unite
```

separate, use **quotes** since we are not refering to objects

```{r}
df_unite %>%
  separate(date, c("year", "month", "day"))
```

## Help

using `?` or `help()`
```{r}
?gather
```

or using the `Help` tab next to the `Packages` tab.

# Reading data | readr


## read_tsv

Guess column types and give **warnings**.

```{r}
library("readr")
soft <- read_tsv("data/GDS5079.soft", skip = 42, na = "null")
```

Viewer utility
```{r, eval=FALSE}
View(soft)
```

## Easier: import file utility


Using `Rstudio`, right top panel. Select directly your **file**.
This actually uses **readr**.

```{r echo=FALSE, out.width='60%'}
knitr::include_graphics("http://lsru.github.io/r_workshop/img/rstudio_import_700.png")
```

# Plotting | ggplot2

[overview](http://rvisualization.com/ggplot2-overview-2/)

## Why tidy is useful?

```{r, out.width='50%'}
library("tidyr")
library("ggplot2")
iris %>%
  gather(flower, measure, 1:4) %>%
  ggplot()+
  geom_boxplot(aes(x = Species, y = measure, fill = flower))
```

## Scatterplots

```{r, out.width='50%'}
iris %>%
  ggplot(aes(x = Sepal.Length, y = Sepal.Width, colour = Species))+
  geom_point()+
  geom_smooth(method = "lm", se = FALSE)+
  xlab("Length")+
  ylab("Width")+
  ggtitle("Sepal")
```

## More aesthetics

```{r, out.width='50%'}
iris %>%
  ggplot(aes(x = Sepal.Length, y = Sepal.Width,
             size = Petal.Length / Petal.Width,
             colour = Species))+
  geom_point()+
  scale_size_area("Petal ratio Length / Width")+
  #scale_colour_brewer(palette = 1, type = "qual")+
  scale_colour_manual(values = c("blue", "red", "orange"))+
  xlab("Sepal.Length")+
  ylab("Sepal.Width")
```

## in / out aesthetics {.columns-2}

```{r, out.width='60%'}
iris %>%
  ggplot(aes(x = Sepal.Length, y = Sepal.Width))+
  geom_point(aes(colour = Species))
```

```{r, out.width='60%'}
iris %>%
  ggplot(aes(x = Sepal.Length, y = Sepal.Width))+
  geom_point(aes(colour = "Species"))
```

## in / out aesthetics

```{r, out.width='60%', eval=FALSE}
iris %>%
  ggplot(aes(x = Sepal.Length, y = Sepal.Width))+
  geom_point(colour = "Species") # Error
```

```{r, out.width='40%'}
iris %>%
  ggplot(aes(x = Sepal.Length, y = Sepal.Width))+
  geom_point(colour = "red")
```

## histogram

```{r, out.width='70%'}
iris_melt %>%
  ggplot()+
  geom_histogram(aes(x = measure, fill = flower))
```

## Barplots - stack

by default, `geom_bar` counts. For mapping values use `stat = "identity"`
```{r, out.width='50%'}
iris_melt %>%
  ggplot()+
  geom_bar(aes(x = Species, y = measure, fill = flower), stat = "identity")
```
```{r, eval=FALSE}
iris_melt %>%
  ggplot()+
  geom_bar(aes(x = measure, fill = flower))
```

## Barplots - relative

```{r, out.width='50%'}
iris_melt %>%
  ggplot()+
  geom_bar(aes(x = Species, y = measure, fill = flower), position = "fill", stat = "identity")
```

## Barplots - dodge
```{r, out.width='50%'}
iris_melt %>%
  ggplot()+
  geom_bar(aes(x = Species, y = measure, fill = flower), position = "dodge", stat = "identity")
```

## heatmap
```{r, out.width='50%'}
iris_melt %>%
  ggplot()+
  geom_tile(aes(x = Species, y = flower, fill = measure))+
  scale_fill_gradient(low = "yellow", high = "red", limits = c(0, 8))
```


## Density and faceting

transparency using the `alpha` parameter
```{r, out.width='50%'}
iris_melt %>%
  ggplot()+
  geom_density(aes(x = measure, fill = Species, colour = Species), alpha = 0.6)+
  facet_wrap(~ flower, scale = "free")+
  theme_bw()
```

## facetting

transparency using the `alpha` parameter
```{r, out.width='50%'}
iris_melt %>%
  ggplot()+
  geom_density(aes(x = measure, fill = Species, colour = Species), alpha = 0.6)+
  facet_grid(Species ~ flower, scale = "free")+
  theme_bw()
```

## theme

```{r, echo=FALSE, out.width='90%'}
light <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width))+
  geom_point(aes(colour = Species))+
  theme_light()+ggtitle("theme_light")
classic <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width))+
  geom_point(aes(colour = Species))+
  theme_classic()+
  theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
        axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'))+
  ggtitle("theme_classic")
void <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width))+
  geom_point(aes(colour = Species))+
  theme_void()+ggtitle("theme_void")
dark <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width))+
  geom_point(aes(colour = Species))+
  theme_dark()+ggtitle("theme_dark")
suppressPackageStartupMessages(library("gridExtra"))
grid.arrange(light, classic, void, dark, nrow = 2)
```


## Recommended reading

- [data structures](http://adv-r.had.co.nz/Data-structures.html) by Hadley
- [R for data science](http://r4ds.had.co.nz) by Hadley & Garrett
  + [reading data](http://r4ds.had.co.nz/data-import.html)
  + [tidy data](http://r4ds.had.co.nz/tidy-data.html)
  + [plotting](http://r4ds.had.co.nz/data-visualisation.html)
- [ggplot2 documentation](http://docs.ggplot2.org/current/) by Hadley / Winston
- [ggplot2 layer by layer](http://rpubs.com/hadley/ggplot2-layers) by Hadley
- [ggplot2 extensions](https://www.ggplot2-exts.org/) by Daniel Emaasit
- Excellent ressource on `R` (in French) 
[Introduction to R](http://egallic.fr/Enseignement/R/m1_stat_eco_logiciel_R.pdf) by Ewen Gallic

## Acknowledgments

* Hadley Wickham
* Garrett Grolemund
* Jenny Bryan
* Ewen Gallic
* David Robinson
* Eric Koncina
* Tony Heurtaux
