---
title: "BADAS: Part I"
subtitle: "`R` brush-up"
author: "Boris Hejblum & Loïc Ferrer"
date: "June 17^th^, 2019"
output:
  html_document:
    toc: yes
    toc_float: yes
    code_folding: show
---

```{r, include=FALSE}
correction <- FALSE
knitr::opts_chunk$set(tidy = TRUE, message = FALSE, eval = correction, echo=correction)
```

# RStudio project setup

 0. Start by opening RStudio and create a new project

# Functions 
 
 1. **Print function**  
 Let's start by writing a function that will print its one argument (e.g. 2).
```{r, eval=TRUE}
myprint <- function(x){
  print(x)
}
```

```{r, eval=TRUE, echo=TRUE}
myprint(2)
```

 
 2. **Default arguments**
 Let's now add a default value to this function's argument
```{r, error=TRUE}
myprint()

myprint_def <- function(x="no name"){
  print(x)
}
myprint_def()
```

# Control structures
 3. **`for` loop**  
 Now consider the following `data.frame`:
```{r, echo=FALSE, eval=TRUE, results='asis'}
hp_df <- cbind.data.frame("first_name" = c("Hermione", "Ron", "Harry"),
                       "last_name" = c("Granger", "Weasley", "Potter"),
                       "gender" = c("female", "male", "male"))
knitr::kable(hp_df)
```  

  Write a function that takes such a `data.frame` as a argument and that will print the last name for each row.

```{r}
print_last_name <- function(x){
  for(i in 1:nrow(x)){
    print(as.character(x[i, "last_name"]))
  }
}
print_last_name(hp_df)
```

 
 4. **`while` statement**
 Now write the same function using a `while` statement.
```{r}
print_last_name_while <- function(x){
  i <- 1
  while(i <= nrow(x)){
    print(as.character(x[i, "last_name"]))
    i <- i + 1
  }
}
print_last_name_while(hp_df)
```

 5. **`if`/`else` statetement**  
 Finally, write a function that will print the last name for females and the first name for males
```{r, echo=correction, eval = correction}
print_last_name_if <- function(x){
  for(i in 1:nrow(x)){
    if(x[i, "gender"] == "female"){
      print(as.character(x[i, "last_name"]))
    }else if(x[i, "gender"] == "male"){
      print(as.character(x[i, "first_name"]))
    }
    
  }
}
print_last_name_if(hp_df)
```
 
> There are only two **hard** things in Computer Science:  
 >      
 >  - cache invalidation, and 
 >  - **naming things**. 
 >
 > -- Phil Karlton