---
title:
output:
  revealjs::revealjs_presentation:
    theme: white
    css: white-edits.css
    highlight: tango
    transition: slide
    self_contained: false
    reveal_plugins: ["chalkboard","search"]
    transitionSpead: fast
    mathjax: "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS_SVG"
    reveal_options:
      minScale: 1.0
      maxScale: 1.0
      width: 1536
      height: 864
      slideNumber: true
      controlsTutorial: true
      chalkboard:
        theme: whiteboard
        readOnly: false
---

## ACCT 420: R Supplement {data-background-video="../Backgrounds/title.mp4" data-background-video-loop=true class="header no-toc-progress present-only" data-state="no-toc-progress"}

<!-- "reveal_plugins:..." and "chalkboard:" are handled by prep38.py -->
```{r helpers, echo=FALSE, warning=FALSE, message=F}
library(knitr)
library(kableExtra)
html_df <- function(text, cols=NULL, col1=FALSE, full=F) {
  if(!length(cols)) {
    cols=colnames(text)
  }
  if(!col1) {
    kable(text,"html", col.names = cols, align = c("l",rep('c',length(cols)-1))) %>%
      kable_styling(bootstrap_options = c("striped","hover"), full_width=full)
  } else {
    kable(text,"html", col.names = cols, align = c("l",rep('c',length(cols)-1))) %>%
      kable_styling(bootstrap_options = c("striped","hover"), full_width=full) %>%
      column_spec(1,bold=T)
  }
}
```

<h3 class="date"><br>Session 1 Supplement</h3>
<h2 class="author"><br>Dr. Richard M. Crowley<br>rcrowley@smu.edu.sg<br><a href="http://rmc.link/">http://rmc.link/</a></h2>

## ACCT 420: R Supplement {data-background="../Backgrounds/title.jpg" class="header no-toc-progress present-not" data-state="no-toc-progress"}

<h3 class="date"><br>Session 1 Supplement</h3>
<h2 class="author"><br>Dr. Richard M. Crowley<br>rcrowley@smu.edu.sg<br><a href="http://rmc.link/">http://rmc.link/</a></h2>


<!-- Load in primary data set -->
```{r, include=FALSE}
library(tidyverse)
df <- read.csv("../../Data/Session_1-2.csv")
# Filter to firms with at least $1M USD revenue, known net income, and fiscal year of 2017
clean_df <- df %>% filter(fyear==2017, !is.na(revt), !is.na(ni), revt > 1)
tech_df <- clean_df %>%
  filter(gsector==45) %>%
  mutate(revenue = revt,
         earnings = ni,
         margin = ni/revt)
earnings_2017 <- tech_df$ni
revenue_2017 <- tech_df$revt
names_2017 <- tech_df$conm
names(earnings_2017) <- names_2017
names(revenue_2017) <- names_2017
```

# Vectors {data-background="../Backgrounds/section.jpg" class="header"}

## Vectors: What are they? {data-background="../Backgrounds/default.jpg" class="default"}

- Remember back to linear algebra...

Examples:

$$
\begin{matrix}
\left(\begin{matrix}
1 \\
2 \\
3 \\
4
\end{matrix}\right) & \text{or} & 
\left(\begin{matrix}
1 & 2 & 3 & 4
\end{matrix}\right)
\end{matrix}
$$

> A row (or column) of data

## Vector creation {data-background="../Backgrounds/default.jpg" class="default"}

- Vectors are entered using the `c()` command
- Any data type is fine, but all elements must be the *same type*

```{r, eval=TRUE}
company <- c("Google", "Microsoft", "Goldman")
company

tech_firm <- c(TRUE, TRUE, FALSE)
tech_firm

earnings <- c(12662, 21204, 4286)
earnings
```

> A vector in R is a 1 dimensional collection of 1 or more of the *same* data type

## Special cases for vectors {data-background="../Backgrounds/default.jpg" class="default"}

<div class="clearfix">
<div class="left">
- Counting between integers
- `:`, e.g. `1:5` or `22:500`
- `seq()`, e.g. `seq(from=0, to=100,` ` by=5)`
```{r}
1:5
seq(from=0, to=100, by=5)
```
<small>$\uparrow$ note that [18] means the 18th output </small>
</div>
<div class="right">
- Repeating something
    - `rep()`, e.g. `rep(1,times=10)` or `rep("hi",times=5)`
```{r}
rep(1,times=10)
rep("hi",times=5)
```
</div>
</div>

## Vector math {data-background="../Backgrounds/default.jpg" class="default"}

> Works the same as scalars, but applies *element-wise*

- First element with first element,
- Second element with second element,
- ...

```{r, eval=TRUE}
earnings  # previously defined
earnings + earnings  # Add element-wise
earnings * earnings  # multiply element-wise
```

## Vector math {data-background="../Backgrounds/default.jpg" class="default"}

> Can also use 1 vector and 1 scalar

- Scalar is applied to all vector elements

```{r, eval=TRUE}
earnings + 10000  # Adding a scalar to a vector
10000 + earnings  # Order doesn't matter
earnings / 1000  # Dividing a vector by a scalar
```

## Vector math {data-background="../Backgrounds/default.jpg" class="default"}

- From linear algebra remember multiplication as a *dot product*.  That can be done with `%*%`

```{r}
# Dot product: sum of product of elements
earnings %*% earnings  # returns a matrix though...
drop(earnings %*% earnings)  # Drop drops excess dimensions
```

- Other useful functions, `length()` and `sum()`:

```{r}
length(earnings)  # returns the number of elements
sum(earnings)  # returns the sum of all elements
```

## Naming vectors {data-background="../Backgrounds/default.jpg" class="default"}

<div class="left">
- Vectors allow us to include a lot of information in one object
    - It isn't easy to read though
- We can make things more readable by assigning `names()`
    - Names provide a way to easily work with and understand the data
</div>
<div class="right">
*Hard to read:*
```{r, eval=TRUE}
earnings
```

*Easy to read:*
```{r, eval=TRUE}
names(earnings) <- c("Google",
                     "Microsoft",
                     "Goldman")
earnings
```
```{r, eval=TRUE}
# Equivalently:
names(earnings) <- company
earnings
```
</div>

## Selecting and combining vectors {data-background="../Backgrounds/default.jpg" class="default"}

<div class="clearfix">
<div class="left">
- Selecting can be done a few ways.
    - By index, such as `[1]`
    - By name, such as `["Google"]`
```{r}
earnings[1]
earnings["Google"]
```
</div>
<div class="right">
- Multiple selection:
    - `earnings[c(1,2)]`
    - `earnings[1:2]`
    - `earnings[c("Google",` `"Microsoft")]`
```{r}
# Each of the above 3 is equivalent
earnings[1:2]
```
- Combining is done using `c()`

```{r}
c1 <- c(1,2,3)
c2 <- c(4,5,6)
c3 <- c(c1,c2)
c3
```
</div>
</div>

## Vector example: Profit margin for tech firms {data-background="../Backgrounds/case.jpg" class="default"}

```{r, eval=TRUE}
# Calculating proit margin for all public US tech firms
# 715 tech firms with >1M sales in 2017
summary(earnings_2017)  # Cleaned data from Compustat, in $M USD
```
<div class="fragment">
```{r, eval=TRUE}
summary(revenue_2017)  # Cleaned data from Compustat, in $M USD
```
</div>
<div class="fragment">
```{r, eval=TRUE}
profit_margin <- earnings_2017 / revenue_2017
summary(profit_margin)
```
</div>
<div class="fragment">
```{r, eval=TRUE}
# These are the worst, midpoint, and best profit margin firms in 2017. Our names carried over :)
profit_margin[order(profit_margin)][c(1,length(profit_margin)/2,length(profit_margin))]
```
</div>

## Practice: Vectors {data-background="../Backgrounds/coding.jpg" class="default"}

- This practice explores the ROA of Goldman Sachs, JPMorgan, and Citigroup in 2017
- Do exercise 2 on the supplementary R practice file:
    - <a href="http://rmc.link/Slides/acct420v4/Session_1_Sup/Session_1_Sup_R.html">R Practice</a>

# Matrices {data-background="../Backgrounds/section.jpg" class="default"}

## Matrices: What are they? {data-background="../Backgrounds/default.jpg" class="default"}

- Remember back to linear algebra...

Example:

$$
\left(\begin{matrix}
1 & 2 & 3 & 4\\
5 & 6 & 7 & 8\\
9 & 10 & 11 & 12
\end{matrix}\right)
$$

> A rows *and* columns of data

## Matrix creation {data-background="../Backgrounds/default.jpg" class="default"}

- Matrices are entered using the `matrix()` command
- Any data type is fine, but all elements must be the *same type*

```{r, eval=TRUE}
columns <- c("Google", "Microsoft", "Goldman")
rows <- c("Earnings","Revenue")

# equivalent: matrix(data=c(12662, 21204, 4286, 110855, 89950, 42254),ncol=3)
firm_data <- matrix(data=c(12662, 21204, 4286, 110855, 89950, 42254),nrow=2)
firm_data

```

## Math with matrices {data-background="../Backgrounds/default.jpg" class="default"}

> Everything with matrices works just like vectors

```{r}
firm_data + firm_data
firm_data / 1000
```

## Matrix math with matrices {data-background="../Backgrounds/default.jpg" class="default"}

- Matrix transposing, $A^T$, uses `t()`
```{r}
firm_data_T <- t(firm_data)
firm_data_T
```
- Matrix multiplication, $A~B$, uses `%*%`
```{r}
firm_data %*% firm_data_T
```

> We won't use these much, but they can be useful

## Matrix naming {data-background="../Backgrounds/default.jpg" class="default"}

- We can name matrix rows and columns, much like we named vector elements
- Use `rownames()` for rows
- Use `colnames()` for columns

```{r}
rownames(firm_data) <- rows
colnames(firm_data) <- columns
firm_data
```

## Selecting from matrices {data-background="../Backgrounds/default.jpg" class="default"}

- Select using 2 indexes instead of 1:
    - `matrix_name[rows,columns]`
    - To select all rows or columns, leave that index blanks

```{r}
firm_data[2,3]
firm_data[,c("Google","Microsoft")]
firm_data[1,]
```

## Combining matrices {data-background="../Backgrounds/default.jpg" class="default"}

- Matrices are combined top to bottom as rows with `rbind()`
- Matrices are combined side-by-side as columns with `cbind()`

```{r,include=FALSE}
indcode <- c(45,45,40)
jpdata <- c(17370, 115475)
# Preloaded: industry codes as indcode (vector)
```

```{r}
# Preloaded: industry codes as indcode (vector)
#     - GICS codes: 40=Financials, 45=Information Technology
#     - See: https://en.wikipedia.org/wiki/Global_Industry_Classification_Standard
# Preloaded: JPMorgan data as jpdata (vector)

mat <- rbind(firm_data,indcode)  # Add a row
rownames(mat)[3] <- "Industry"  # Name the new row
mat
mat <- cbind(firm_data,jpdata)  # Add a column
colnames(mat)[4] <- "JPMorgan"  # Name the new column
mat
```

# Lists {data-background="../Backgrounds/section.jpg" class="default"}

## Lists: What are they? {data-background="../Backgrounds/default.jpg" class="default"}

- Like vectors, but with mixed types
- Generally not something we will create
- Often returned by analysis functions in R
    - Such as the linear models we will look at next week

```{r}
# Ignore this code for now...
model <- summary(lm(earnings ~ revenue, data=tech_df))
#Note that this function is hiding something...
model
```

## Looking into lists {data-background="../Backgrounds/default.jpg" class="default"}

- Lists generally use double square brackets, `[[index]]`
    - Used for pulling individual elements out of a list
- `[[c()]]` will drill through lists, as opposed to pulling multiple values
- Single square brackets pull out elements as is
- Double square brackets extract just the element
- For 1 level, we can also use `$`

<div class="clearfix">
<div class="left">
```{r}
model["r.squared"]
model[["r.squared"]]
model$r.squared
```
</div>
<div class="right">
```{r}
earnings["Google"]
earnings[["Google"]]
#Can't use $ with vectors
```
</div>
</div>

## Structure of a list {data-background="../Backgrounds/default.jpg" class="default"} 
- `str()` will tell us what's in this list

```{r}
str(model)
```

## Practice: Lists {data-background="../Backgrounds/coding.jpg" class="default"}

- In this practice, we will explore lists and how to parse them
- Do exercise 3 on the supplementary R practice file:
    - <a href="http://rmc.link/Slides/acct420v4/Session_1_Sup/Session_1_Sup_R.html">R Practice</a>

# Data frames {data-background="../Backgrounds/section.jpg" class="header"}

## What are data frames? {data-background="../Backgrounds/default.jpg" class="default"}

- Data frames are like a hybrid between lists and matrices

<div class="clearfix">
<div class="left">
Like a matrix:

- 2 dimensional like matrices
- Can access data with `[]`
- All elements in a column must be the same data type
</div>
<div class="right">
Like a list:

- Can have different data types for different columns
- Can access data with `$`
</div>
</div>

> Think of columns as variables, rows as observations

## Example of a data frame {data-background="../Backgrounds/default.jpg" class="default"}

```{r, warning=FALSE}
library(DT)  # This library is great for including larger collections of data in output
datatable(tech_df[1:20,c("conm","tic","margin")], rownames=FALSE)
```

## How to create data frames {data-background="../Backgrounds/default.jpg" class="default"}

1. On import of data, usually you will get a data frame
2. Using the `data.frame()` function

```{r}
df <- data.frame(companyName=company,
                 earnings=earnings,
                 tech_firm=tech_firm)
df
```

> Note: `stringsAsFactors=FALSE` is no longer needed as of R 4.0.0

## Selecting from data frames {data-background="../Backgrounds/default.jpg" class="default"}

- Access like a matrix
```{r}
df[,1]
```
- Access like a list
```{r}
df$companyName
df[[1]]
```

> All are relatively equivalent.  Using `$` is generally most natural.  Using `[,]` is good for complex references.

## Making new columns in a data frame {data-background="../Backgrounds/default.jpg" class="default"}

> Suggested method: use `$`

```{r}
df$all_zero <- 0
df$revenue <- c(110855, 89950, 42254)
df$margin <- df$earnings / df$revenue
# Custom function for small tables -- see last slide for code
html_df(df)
```

> Alternative method: use `cbind()` just like with matrices

## Sorting data frames {data-background="../Backgrounds/default.jpg" class="default"}

- To sort a *vector*, we could use the `sort()`

```{r}
sort(df$earnings)
```

> THIS CAN'T SORT DATA FRAMES

- A column of a data frame is fine, but it can't sort the whole thing!

## Sorting data frames {data-background="../Backgrounds/default.jpg" class="default"}

- To sort a data frame, we use the `order()` function
    - It returns the order of each element in increasing value
        - 1 is the lowest value
    - Then we pass the new order like we are selecting elements

```{r}
ordering <- order(df$earnings)
ordering
df <- df[ordering,]
df
```

## Sorting data frames {data-background="../Backgrounds/default.jpg" class="default"}

- Order can sort by multiple levels
    - `order(level1,level2,...)`, where `level_` are vectors or data frame columns

```{r}
# Example of multicolumn sorting:
example <- data.frame(firm=c("Google","Microsoft","Google","Microsoft"),
                      year=c(2017,2017,2016,2016))
example

# with() allows us to avoiding prepending each column with "example$"
ordering <- order(example$firm, example$year)
example <- example[ordering,]
example
```
    

## Subsetting data frames {data-background="../Backgrounds/default.jpg" class="default"}

1. We can use the selecting methods from before
2. We can pass a vector of logical values telling R what to keep
    - This is pretty useful!

```{r}
df[df$tech_firm,]  # Remember the comma!
```

3. We can use the `subset()` function
     - I don't recommend this function, as it <a href="http://adv-r.had.co.nz/Computing-on-the-language.html">does not always work</a>
         - There are times where it is useful though

```{r}
subset(df,earnings < 20000)
```

## Practice: Data frames {data-background="../Backgrounds/coding.jpg" class="default"}

- This exercise explores the nature of banks' deposits
    - We will see which of Goldman, JPMorgan, and Citigroup have (since 2010):
        - The least of their assets in deposits
        - The most of their assets in deposits
- Do exercise 4 on the supplementary R practice file:
    - <a href="http://rmc.link/Slides/acct420v4/Session_1_Sup/Session_1_Sup_R.html">R Practice</a>

# Logical expressions {data-background="../Backgrounds/section.jpg" class="header"}

## Why use logical expressions? {data-background="../Backgrounds/default.jpg" class="default"}

- We just saw an example in our subsetting function
    - `earnings < 20000`
- Logical expressions give us more control over the data
- They let us easily create logical vectors for subsetting data

```{r}
df$earnings
df$earnings < 20000
```

## Logical operators {data-background="../Backgrounds/default.jpg" class="default"}

`==` `!=` `>` `<` `>=` `<=` `!` `|` `&`

<div class="clearfix">
<div class="left">
- Equals: `==`
    - `2 == 2` $\rightarrow$ `r 2 == 2`
    - `2 == 3` $\rightarrow$ `r 2 == 3`
    - `'dog'=='dog'` $\rightarrow$ `r 'dog'=='dog'`
    - `'dog'=='cat'` $\rightarrow$ `r 'dog'=='cat'`
</div>
<div class="right">
- Not equals: `!=`
    - The opposite of `==`
    - `2 != 2` $\rightarrow$ `r 2 != 2`
    - `2 != 3` $\rightarrow$ `r 2 != 3`
    - `'dog'!='cat'` $\rightarrow$ `r 'dog'!='cat'`
</div>
</div>

- Comparing strings is done character by character
    - Be very careful with it

## Logical operators {data-background="../Backgrounds/default.jpg" class="default"}

`==` `!=` `>` `<` `>=` `<=` `!` `|` `&`

<div class="clearfix">
<div class="left">
- Greater than: `>`
    - `2 > 1` $\rightarrow$ `r 2 > 1`
    - `2 > 2` $\rightarrow$ `r 2 > 2`
    - `2 > 3` $\rightarrow$ `r 2 > 3`
    - `'dog'>'cat'` $\rightarrow$ `r 'dog'>'cat'`
</div>
<div class="right">
- Less than: `>`
    - `2 < 1` $\rightarrow$ `r 2 < 1`
    - `2 < 2` $\rightarrow$ `r 2 < 2`
    - `2 < 3` $\rightarrow$ `r 2 < 3`
    - `'dog'<'cat'` $\rightarrow$ `r 'dog'<'cat'`
</div>
</div>
<div class="clearfix">
<div class="left">
- Greater than or equal to: `>`
    - `2 >= 1` $\rightarrow$ `r 2 >= 1`
    - `2 >= 2` $\rightarrow$ `r 2 >= 2`
    - `2 >= 3` $\rightarrow$ `r 2 >= 3`
</div>
<div class="right">
- Less than or equal to: `>`
    - `2 <= 1` $\rightarrow$ `r 2 <= 1`
    - `2 <= 2` $\rightarrow$ `r 2 <= 2`
    - `2 <= 3` $\rightarrow$ `r 2 <= 3`
</div>
</div>

## Logical operators {data-background="../Backgrounds/default.jpg" class="default"}

- Not: `!`
    - This simply inverts everything
    - `!TRUE` $\rightarrow$ `r !TRUE`
    - `!FALSE` $\rightarrow$ `r !FALSE`
- And: `&`
    - `TRUE & TRUE` $\rightarrow$ `r TRUE & TRUE`
    - `TRUE & FALSE` $\rightarrow$ `r TRUE & FALSE`
    - `FALSE & FALSE` $\rightarrow$ `r FALSE & FALSE`
- Or: `|` (pipe, same key as '\\')
    - Note that `|` is evaluated after all `&`s
    - `TRUE | TRUE` $\rightarrow$ `r TRUE | TRUE`
    - `TRUE | FALSE` $\rightarrow$ `r TRUE | FALSE`
    - `FALSE | FALSE` $\rightarrow$ `r FALSE | FALSE`
- You can mix in parentheses for grouping as needed

## Examples for logical operators {data-background="../Backgrounds/case.jpg" class="default"}

- How many tech firms had >\$10B in revenue in 2017?

```{r}
sum(tech_df$revenue > 10000)
```

- How many tech firms had >\$10B in revenue but had negative earnings in 2017?

```{r}
sum(tech_df$revenue > 10000 & tech_df$earnings < 0)
```

- Who are those 4 with high revenue and negative earnings?

```{r}
columns <- c("conm","tic","earnings","revenue")
tech_df[tech_df$revenue > 10000 & tech_df$earnings < 0, columns]
```

## Other special values {data-background="../Backgrounds/default.jpg" class="default"}

- We know `TRUE` and `FALSE` already
    - Note that `FALSE` can be represented as 0
    - Note that `TRUE` can be represented as any non-zero number
- There are also:
    - `Inf`: Infinity, often caused by dividing something by 0
    - `NaN`: "Not a number," likely that the expression 0/0 occurred
    - `NA`: A missing value, usually *not* due to a mathematical error
    - `Null`: Indicates a variable has nothing in it
- We can check for these with:
    - `is.inf()`
    - `is.nan()`
    - `is.na()`
    - `is.null()`

## Practice: Subsetting our data frame {data-background="../Backgrounds/coding.jpg" class="default"}

- This practice focuses on subsetting out potentially interesting parts of our data frame
    - We will also see which of Goldman, JPMorgan, and Citigroup, in which year, had the lowest earnings since 2010
- Do exercise 5 on the supplementary R practice file:
    - <a href="http://rmc.link/Slides/acct420v4/Session_1_Sup/Session_1_Sup_R.html">R Practice</a>

## Other uses {data-background="../Backgrounds/default.jpg" class="default"}

- Conditional statements (used for programming)

```{r, eval=FALSE}
# cond1, cond2, etc. can be any logical expression
if(cond1) {
  # Code runs if cond1 is TRUE
} else if (cond2) { # Can repeat 'else if' as needed
  # Code runs if this is the first condition that is TRUE
} else {
  # Code runs if none of the above conditions TRUE
}
```

- Vectorized conditional statements using `ifelse()`
    - If else takes 3 vectors and returns 1 vector
        - A vector of `TRUE` or `FALSE`
        - A vector of elements to return from when `TRUE`
        - A vector of elements to return from when `FALSE`

```{r}
# Outputs odd for odd numbers and even for even numbers
even <- rep("even",5)
odd <- rep("odd",5)
numbers <- 1:5
ifelse(numbers %% 2, odd, even)
```

# Loops and apply {data-background="../Backgrounds/section.jpg" class="header"}

## Looping: While loop {data-background="../Backgrounds/section.jpg" class="header"}

<div class="clearfix">
<div class="left">
<img src="../Figures/while-loop.png">
</div>
<div class="right">
- A `while()` loop executes code repeatedly until a specified condition is `FALSE`

```{r}
i = 0
while(i < 5) {
  print(i)
  i = i + 2
}
```
</div>

## Looping: For loop {data-background="../Backgrounds/section.jpg" class="header"}

<div class="clearfix">
<div class="left">
<img src="../Figures/for-loop.png">
</div>
<div class="right">
- A `for()` loop executes code repeatedly until a specified condition is `FALSE`, while incrementing a given variable

```{r}
for(i in c(0,2,4)) {
  print(i)
}
```
</div>

## Dangers of looping in R {data-background="../Backgrounds/section.jpg" class="header"}

- Loops in R are very slow -- they do one calculation at a time, but R is best for doing many calculations at once

<div class="clearfix">
<div class="left">
```{r}
# Profit margin, all US tech firms
start <- Sys.time()
margin_1 <- rep(0,length(tech_df$ni))
for(i in seq_along(tech_df$ni)) {
  margin_1[i] <- tech_df$earnings[i] /
                 tech_df$revenue[i]
}
end <- Sys.time()
time_1 <- end - start
time_1
```
</div>
<div class="right">
```{r}
# Profit margin, all US tech firms
start <- Sys.time()
margin_2 <- tech_df$earnings /
            tech_df$revenue
end <- Sys.time()
time_2 <- end - start
time_2
```
</div>
</div>

```{r}
identical(margin_1, margin_2)  # Are these calculations identical?  Yes they are.
paste(as.numeric(time_1) / as.numeric(time_2), "times") # How much slower is the loop?
```

# Useful functions {data-background="../Backgrounds/section.jpg" class="header"}

## Help functions {data-background="../Backgrounds/reference.jpg" class="default"}

- There are two equivalent ways to quickly access help files:
    - `?` and `help()`
    - Usage to get the help file for `data.frame()`:
        - `?data.frame`
        - `help(data.frame)`
- To see the options for a function, use `args()`

```{r}
args(data.frame)
```

## A note on using functions {data-background="../Backgrounds/reference.jpg" class="default"}

```{r}
args(data.frame)
```

- The `...`  represents a series of inputs
    - In this case, inputs like `name=data`, where name is the column name and data is a vector
- The `____ = ____` arguments are options for the function
    - The default is prespecified, but you can overwrite it
- Options can be very useful or save us a lot of time!
- You can always find them by:
    - Using the `?` command
    - Checking other documentation like <a href="www.rdocumentation.org">www.rdocumentation.org</a>
    - Using the `args()` function

## Installing more functions {data-background="../Backgrounds/reference.jpg" class="default"}

- R Provides an easy way to install packages without ever leaving R
    - The `install.packages()` command
    - Can install a single package or a vector of packages

```{r, eval=FALSE}
# To install the tidyverse package:
install.packages("tidyverse")

# To install ggplot2, dplyr, and magrittr packages:
install.packages(c("ggplot2", "dplyr", "magrittr"))
```

- Load packages using `library()`
    - Need to do this each time you open a new instance of R

```{r, eval=FALSE}
# Load the tidyverse package
library(tidyverse)
```

## Pipe notation {data-background="../Backgrounds/reference.jpg" class="default"}

> Pipe notation is never necessary and not built in to R

- Pipe notation is provided by the `package:magrittr` package
    - Part of `package:tidyverse`, an extremely popular collection of packages
- Pipe notation is done using `%>%`
    - `Left %>% Right(arg2, ...)` is the same as `Right(Left, arg2, ...)`

> Piping can drastically improve code readability

## Piping example {data-background="../Backgrounds/default.jpg" class="default"}

> Plot tech firms' earnings vs revenue, >\$10B in revenue

```{r, echo=TRUE, warning=FALSE, message=FALSE, fig.height = 3, fig.width = 5}
library(tidyverse)
library(plotly)

plot <- tech_df %>%
  subset(revenue > 10000) %>%
  ggplot(aes(x=revenue,y=earnings)) + # ggplot comes from ggplot2, part of tidyverse
  geom_point(shape=1, aes(text=sprintf("Ticker: %s", tic)))  # Adds point, and ticker
ggplotly(plot)  # Makes the plot interactive
```

## Piping example: Without piping {data-background="../Backgrounds/default.jpg" class="default"}

```{r, echo=TRUE, warning=FALSE, message=FALSE, fig.height = 3, fig.width = 5}
library(tidyverse)
library(plotly)

plot <- ggplot(subset(tech_df, revenue > 10000), aes(x=revenue,y=earnings)) +
  geom_point(shape=1, aes(text=sprintf("Ticker: %s", tic)))
ggplotly(plot)  # Makes the plot interactive
```

## Practice: External library usage {data-background="../Backgrounds/coding.jpg" class="default"}

- This practice focuses on using an external library
    - We will also see which of Goldman, JPMorgan, and Citigroup, in which year, had the lowest earnings since 2010
- Do exercise 6 on the supplementary R practice file:
    - <a href="http://rmc.link/Slides/acct420v4/Session_1_Sup/Session_1_Sup_R.html">R Practice</a>

> Note: The ~ indicates a formula the left side is the y-axis and the right side is the x-axis

> Note: The | tells lattice to make panels based on the variable(s) to the right

## Math functions {data-background="../Backgrounds/default.jpg" class="default"}

- `sum()`: Sum of a vector
- `abs()`: Absolute value
- `sign()`: The sign of a number

```{r}
vector = c(-2,-1,0,1,2)
sum(vector)
abs(vector)
sign(vector)
```

## Stats functions {data-background="../Backgrounds/default.jpg" class="default"}

- `mean()`: Calculates the mean of a vector
- `median()`: Calculates the median of a vector
- `sd()`: Calculates the sample standard deviation of a vector
- `quantile()`: Provides the *quartiles* of a vector
- `range()`: Gives the minimum and maximum of a vector
    - Related: `min()` and `max()`

```{r}
quantile(tech_df$earnings)
range(tech_df$earnings)
```

## Make your own functions! {data-background="../Backgrounds/default.jpg" class="default"}

- Use the `function()` function!
    - `my_func <- function(agruments) {code}`

> Simple function: Add 2 to a number

```{r}
add_two <- function(n) {
  n + 2
}

add_two(500)
```

## Slightly more complex function example {data-background="../Backgrounds/default.jpg" class="default"}

```{r}
mult_together <- function(n1, n2=0, square=FALSE) {
  if (!square) {
    n1 * n2
  } else {
    n1 * n1
  }
}

mult_together(5,6)
mult_together(5,6,square=TRUE)
mult_together(5,square=TRUE)
```

## Practice: Functions {data-background="../Backgrounds/coding.jpg" class="default stack"}

- This practice focuses on making a custom function
    - Currency conversion between USD and SGD!
        - A web-based example is in the end notes
- Do exercise 7 on the supplementary R practice file:
    - <a href="http://rmc.link/Slides/acct420v4/Session_1_Sup/Session_1_Sup_R.html">R Practice</a>

# End Matter {data-background="../Backgrounds/ending.jpg" class="default"}

## Wrap up {data-background="../Backgrounds/ending.jpg" class="default stack"}

> Having completed these slides, you should be ready for any R code in the class!

## Packages used for these slides {data-background="../Backgrounds/code.jpg" class="default stack"}

- `package:DT`
- `package:kableExtra`
- `package:knitr`
- `package:plotly`
- `package:quantmod`
- `package:revealjs`
- `package:RColorBrewer`
- `package:tidyverse`


## Custom functions {data-background="../Backgrounds/code.jpg" class="default stack"}

<small style="width:100%">
```{r, eval=FALSE}
# Custom code for small tables from dataframes
library(knitr)
library(kableExtra)
html_df <- function(text, cols=NULL, col1=FALSE, full=F) {
  if(!length(cols)) {
    cols=colnames(text)
  }
  if(!col1) {
    kable(text, "html", col.names=cols, align=c("l", rep('c',length(cols)-1))) %>%
      kable_styling(bootstrap_options=c("striped","hover","responsive"), full_width=full)
  } else {
    kable(text, "html", col.names=cols, align=c("l", rep('c',length(cols)-1))) %>%
      kable_styling(bootstrap_options=c("striped", "hover","responsive"), full_width=full) %>%
      column_spec(1,bold=T)
  }
}
```

```{r, eval=FALSE}
# Custom code for pulling 1 day of ForEx data from OANDA
FXRate <- function(from="USD", to="SGD", dt=Sys.Date()) {
  options("getSymbols.warning4.0"=FALSE)
  require(quantmod)
  data <- getSymbols(paste0(from, "/", to), from=dt-1, to=dt, src="oanda", auto.assign=F)
  return(data[[1]])
}
```

</small>

## NOTES {class="never"}

Shift some easier content to week 1, perhaps 1 exercise

Consider shifting matrix algebra and such to appendix
