## Announcement

- Just stay warm and dry.

## R basics


### styles
(reading assignment)

Checkout [Style guide in Advanced R](http://adv-r.had.co.nz/Style.html#undefined)
and the [tidyverse style guide](https://style.tidyverse.org/).

### Arithmetic

R can do any basic mathematical computations.

|symbol | use |
|:-------|:---------|
| + | addition |
| - | subtraction |
| * | multiplication |
| / | division |
| ^ | power |
| %% | modulus |
| exp() | exponent |
| log() | natural logarithm |
| sqrt() | square root |
| round() | rounding |
| floor() | flooring |
| ceiling() | ceiling |

### Objects

You can create an R object to save results of a computation or other command.

Example 1

```{r}
x <- 3 + 5
x
```

 - In most languages, the direction of passing through the value into the object goes from right to left (e.g. with "=").
However, R allows both directions (which is actually bad!).
In this course, we encourage the use of "<-" or "=".
There are people liking "=" over "<-" for the reason that "<-" sometimes break into two operators "< -".

Example 2
```{r}
x < - 3 + 5
x
```

 - For naming conventions, stick with either "." or "_" (refer to the style guide).

Example 3
```{r}
sum.result <- x + 5
sum.result
```

 - _important_: many names are already taken for built-in R functions.
Make sure that you don't override them.

Example 4
```{r}
sum(2:5)
sum
sum <- 3 + 4 + 5
sum(5:8)
sum
```

 - R is case-sensitive. "Math.7260" is different from "math.7260".
 
### Locating and deleting objects:
The commands "objects()" and "ls()" will provide a list of every object that you've created in a session.

```{r}
objects()

ls()
```

The "rm()" and "remove()" commands let you delete objects (tip: always clearn-up your workspace as the first command)

```{r}
rm(list=ls())  # clean up workspace
```

### Vectors

Many commands in R generate a vector of output, rather than a single number.

The "c()" command: creates a vector containing a list of specific elements.

Example 1

```{r}
c(7, 3, 6, 0)
c(73:60)
c(7:3, 6:0)
c(rep(7:3, 6), 0)
```

Example 2
The command "seq()" creates a sequence of numbers.
```{r}
seq(7)
seq(3, 70, by = 6)
seq(3, 70, length = 6)
```


### Operations on vectors

Use brackets to select element of a vector.

```{r}
x <- 73:60
x[2]
x[2:5]
x[-(2:5)]
```

Can access by "name" (safe with column/row order changes)

```{r}
y <- 1:3
names(y) <- c("do", "re", "mi")
y[3]
y["mi"]
```

R commands on vectors

| command | usage |
|:---------|:-------|
| sum()   | sum over elements in vector |
| mean()  | compute average value |
|sort() | sort elements in a vector |
| min(), max() | min and max values of a vector|
|length() | length of a vector |
|summary() | returns the min, Q1, median, mean, Q3, and max values of a vector |
| sample(x, size, replace = FALSE, prob = NULL) | takes a random sample from a vector with or without replacement|

**Exercise**
Write a command to generate a random permutation of the numbers between 1 and 5 and save it to an object.


### Matrix

matrix() command creates a matrix from the given set of values

```{r}
matrix.example <- matrix(rnorm(100), nrow = 10, ncol = 10, byrow = TRUE)
matrix.example
```


### R commands on vector/matrix

| command | usage |
|---------|-------|
| sum()   | sum over elements in vector/matrix |
| mean()  | compute average value |
|sort() | sort all elements in a vector/matrix |
| min(), max() | min and max values of a vector/matrix|
| length() | length of a vector/matrix |
|summary() | returns the min, Q1, median, mean, Q3, and max values of a vector |
| dim() | dimension of a matrix |
| cbind() | combine a sequence of vector, matrix or data-frame arguments and combine by columns |
| rbind() | combine a sequence of vector, matrix or data-frame arguments and combine by rows |
| names() | get or set names of an object |
| colnames() | get or set column names of a matrix-like object |
| rownames() | get or set row names of a matrix-like object |
<!-- | sample(x, size, replace = FALSE, prob = NULL) | takes a random sample from a vector with or without replacement| -->

```{r}
sum(matrix.example)
mean(matrix.example)
sort(matrix.example)
summary(matrix.example)
```

**Exercise**
Write a command to generate a random permutation of the numbers between 1 and 5 and save it to an object.


<!--
```{r}
order(runif(5))
sample(1:5, 5)
```
-->

### Comparison (logic operator)
|symbol | use |
|-------|---------|
| != | not equal |
| == | equal |
| >  | greater |
| >= | greater or equal |
| <  | smaller |
| <= | smaller or equal |
| is.na | is it "Not Available"/Missing |
| complete.cases | returns a logical vector specifying which observations/rows have no missing values |
| is.finite | if the value is finite |
| all | are all values in a logical vector true? |
| any | any value in a logical vector is true? |

```{r}
test.vec <- 73:68
test.vec

test.vec < 70

test.vec > 70

test.vec[3] <- NA
test.vec

is.na(test.vec)

complete.cases(test.vec)

all(is.na(test.vec))
any(is.na(test.vec))
```

Now let's do a test of accuracy for doubles in R.
Recall that for _Double_ precision, we get approximately $\log_{10}(2^{52}) \approx 16$ decimal point for precision.

```{r}
test.exponent <- -(7:18)
10^test.exponent == 0
1 - 10^test.exponent == 1
7360 - 10^test.exponent == 7360
73600 - 10^test.exponent == 73600
```

### Other operators

%in%, match

```{r}
test.vec
66 %in% test.vec

match(66, test.vec, nomatch = 0)

70 %in% test.vec

match(70, test.vec, nomatch = 0)

match(70, test.vec, nomatch = 0) > 0 # the implementation of %in%

```


### Control flow

These are the basic control-flow constructs of the R language. They function in much the same way as control statements in any Algol-like (Algol short for "Algorithmic Language") language. They are all reserved words.

| keyword | usage |
| ------- | ----- |
| if | **if**(_cond_) _expr_ |
| if-else | **if**(_cond_) _cons.expr_ **else** _alt.expr_ |
| for  | **for**(_var_ **in** _seq_) _expr_ |
| while | **while**(_cond_) _expr_ |
| break | breaks out of a _for_ loop |
| next | halts the processing of the current iteration and advances the looping index|


### Define a function

Read [Function](http://adv-r.had.co.nz/Functions.html) section from Advanced R by Hadley Wickham.
We will visit functions in more details.

```{r}
DoNothing <- function() {
  return(invisible(NULL))
}
DoNothing()
```

In general, try to avoid using loops (vectorize your code) in R.
If you have to loop, try using **for** loops first.
Sometimes, **while** loops can be dangerous (however, a smart _compiler_ should detect this).

```{r}
DoBadThing <- function() {
  result <- NULL
  while(TRUE) {
    result <- c(result, rnorm(100))
  }
  return(result)
}
# DoBadThing()
```


### Install packages

You can install R packages from several places ([reference](https://r-coder.com/install-r-packages/)):

- Comprehensive R Archive Network (CRAN)
  
  - Official R packages repository
  
  - Some levels of code checks (cross platform support, version control etc)
  
  - Most common place you will install packages
  
  - Pick a mirror location near you
  
  - `install.packages("packge_name")`

- GitHub

  - May get development version of a package
  
  - Almost zero level of code checks
  
  - Common place to develop a package before submitting to CRAN
    ```{r, eval = FALSE}
    install.packages("devtools")
    library(devtools)
    install_github("tidyverse/ggplot2")
    ```
    
### Load packages

```{r}
library(tidyverse)
require(tidyverse)
```