---
title: "ACCT 420: R Supplement"
author: 
  - name: Dr. Richard M. Crowley
    email: rcrowley@smu.edu.sg
    affiliation: https://rmc.link/
title-slide-attributes:
  data-background-video: "../Backgrounds/title.mp4"
  data-background-video-loop: "true"
  data-background-size: stretch
format:
  revealjs:
    theme: default
    css: quarto_white.css
    navigation-mode: vertical
    controls: true
    transition: slide
    background-transition: fade
    transition-speed: default
    width: 1536
    height: 864
    logo: ../Logos/logo2.png
    code-link: true
    code-line-numbers: false
    chalkboard:
      theme: whiteboard
    auto-stretch: false
revealjs-plugins:
  - attribution
execute:
  echo: true
  warning: false
  message: false
editor: source
---

# Vectors {data-background-video="../Backgrounds/section.mp4"}

<!--# Note that the downlit and xml2 pacakges are required to compile -->
<!--# Installed extensions include `attribution`, `qrcode`, and `material-icons` -->

```{r helpers, echo=FALSE, warning=FALSE, message=F}
library(knitr)
library(kableExtra)

#' Pretty formatted HTML tables
#' 
#' @param df The dataframe to format as a table
#' @param names Names to use for columns if not using the df column names. Vector
#' @param highlight_cols Columns to highlight. Default is c(1) for highlighting the first row. Use c() to remove.
#' @param highlight_rows Rows to highlight. Default is c() to not highlight any rows.
#' @param color_rows Rows to highlight in color. Default is c() to not highlight any rows.
#' @param highlight_end_rows Rows to highlight. Uses a reverse indexing where 1 is the last row, 2 is second to last, etc.
#' @param full Use to span the full width of a slide. FALSE by default.
#' @param fixed_header Whether the first row should be treated as a header row. TRUE by default.
html_df <- function(df, names=NULL, highlight_cols=c(1), highlight_rows=c(), color_rows=c(), highlight_end_rows=c(), full=F, fixed_header=T) {
  if(!length(names)) {
    names=colnames(df)
  }
  kbl(df,"html", col.names = names, align = c("l",rep('c',length(cols)-1))) %>%
    kable_paper(c("striped","hover"), full_width=full, fixed_thead=F, html_font = "\"Source Sans Pro\", Helvetica, sans-serif") %>%
    {if(length(highlight_cols)) column_spec(., highlight_cols,bold=T, background = "#ffffff99") else .} %>%
    {if(length(highlight_rows)) row_spec(., highlight_rows,bold=T, background = "#ffffff99") else .} %>%
    {if(length(color_rows)) row_spec(., color_rows,bold=T, background = "#aaaaff99") else .} %>%
    {if(length(highlight_end_rows)) row_spec(., nrow(df) + 1 - highlight_end_rows,bold=T, background = "#ffffff99") else .}
}

library(tidyverse)
```

<!--# List pacakges here that are not being correctly highlighted -->
<!--# The usual cause is calling the library from a echo=FALSE cell -->

```{r}
#| include: false
options(downlit.attached = c("knitr", "kableExtra", "tidyverse"))
```



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

- 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"}

- 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"}

:::: {.columns}

::: {.column width="50%"}
- 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 [20] means the 20th output </small>

:::

::: {.column width="50%"}
- Repeating something
    - `rep()`, e.g. `rep(1,times=10)` or `rep("hi",times=5)`
```{r}
rep(1,times=10)
rep("hi",times=5)
```
:::

::::

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

> 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"}

> 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"}

- From linear algebra, remember multiplication via 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"}

:::: {.columns}

::: {.column width="50%"}
- 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
:::

::: {.column width="50%"}
*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
```
:::

::::


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

:::: {.columns}

::: {.column width="50%"}
- Selecting can be done a few ways.
    - By index, such as `[1]`
    - By name, such as `["Google"]`
```{r}
earnings[1]
earnings["Google"]
```
:::

::: {.column width="50%"}
- 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
```
:::

::::

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


<!-- 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
```

```{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"}

- This practice explores the ROA of Goldman Sachs, JPMorgan, and Citigroup in 2017
- Do exercises 1 and 2 on the supplementary R practice file:
    - <a href="https://rmc.link/acct420r1sup">R Practice</a>
    - Short link: [rmc.link/acct420r1sup](https://rmc.link/acct420r1sup)

# Matrices {data-background-video="../Backgrounds/section.mp4"}

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

- 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"}

- 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"}

> Everything with matrices works just like vectors

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

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

- 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"}

- 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"}

- 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"}

- 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-video="../Backgrounds/section.mp4"}

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

- Like vectors, but with mixed types
- Generally not something we will create
- Often returned by analysis functions in R

```{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"}

- 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 `$`

:::: {.columns}

::: {.column width="50%"}
```{r}
model["r.squared"]
model[["r.squared"]]
model$r.squared
```
:::

::: {.column width="50%"}
```{r}
earnings["Google"]
earnings[["Google"]]
#Can't use $ with vectors
```
:::

::::

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

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

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

- In this practice, we will explore lists and how to parse them
- Do exercise 3 on the supplementary R practice file:
    - <a href="https://rmc.link/acct420r1sup">R Practice</a>
    - Short link: [rmc.link/acct420r1sup](https://rmc.link/acct420r1sup)

# Data frames {data-background-video="../Backgrounds/section.mp4"}

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

- Data frames are like a hybrid between lists and matrices

:::: {.columns}

::: {.column width="50%"}
Like a matrix:

- 2 dimensional like matrices
- Can access data with `[]`
- All elements in a column must be the same data type
:::

::: {.column width="50%"}
Like a list:

- Can have different data types for different columns
- Can access data with `$`
:::

::::

> Think of columns as variables, rows as observations

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

```{r, echo=F}
library(DT) # This library is great for including larger collections of data in output
options(DT.options = list(scrollY="450px"))
```

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

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

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"}

- 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"}

> 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"}

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

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

::: {.callout-warning}

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"}

- 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"}

- 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"}

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"}

- 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="https://rmc.link/acct420r1sup">R Practice</a>
    - Short link: [rmc.link/acct420r1sup](https://rmc.link/acct420r1sup)

# Logical expressions {data-background-video="../Backgrounds/section.mp4"}

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

- 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"}

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

:::: {.columns}

::: {.column width="50%"}
- 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'`
:::

::: {.column width="50%"}
- Not equals: `!=`
    - The opposite of `==`
    - `2 != 2` $\rightarrow$ `r 2 != 2`
    - `2 != 3` $\rightarrow$ `r 2 != 3`
    - `'dog'!='cat'` $\rightarrow$ `r 'dog'!='cat'`
:::

::::

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

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

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

:::: {.columns}

::: {.column width="50%"}
- 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'`
:::

::: {.column width="50%"}
- 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'`
:::

::::

:::: {.columns}

::: {.column width="50%"}
- Greater than or equal to: `>`
    - `2 >= 1` $\rightarrow$ `r 2 >= 1`
    - `2 >= 2` $\rightarrow$ `r 2 >= 2`
    - `2 >= 3` $\rightarrow$ `r 2 >= 3`
:::

::: {.column width="50%"}
- Less than or equal to: `>`
    - `2 <= 1` $\rightarrow$ `r 2 <= 1`
    - `2 <= 2` $\rightarrow$ `r 2 <= 2`
    - `2 <= 3` $\rightarrow$ `r 2 <= 3`
:::

::::


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

- 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"}

- 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"}

- 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"}

- 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="https://rmc.link/acct420r1sup">R Practice</a>
    - Short link: [rmc.link/acct420r1sup](https://rmc.link/acct420r1sup)

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

- 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
        1. A vector of `TRUE` or `FALSE`
        2. A vector of elements to return from when `TRUE`
        3. 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-video="../Backgrounds/section.mp4"}

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

:::: {.columns}

::: {.column width="50%"}
![](../Figures/while-loop.png){width="400px" fig-align="center"}
:::

::: {.column width="50%"}
- A `while()` loop executes code repeatedly until a specified condition is `FALSE`

```{r}
i = 0
while(i < 5) {
  print(i)
  i = i + 2
}
```
:::

::::

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

:::: {.columns}

::: {.column width="50%"}
![](../Figures/for-loop.png){width="400px" fig-align="center"}
:::

::: {.column width="50%"}
- 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)
}
```
:::

::::


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

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

:::: {.columns}

::: {.column width="50%"}
```{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
```
:::

::: {.column width="50%"}
```{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
```
:::

::::

```{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-video="../Backgrounds/section.mp4"}

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

- 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"}

```{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"}

- 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"}

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

- Pipe notation is provided by the `{magrittr}` package
    - Part of `{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"}

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

```{r}
#| eval: true
#| echo: true
#| fig-width: 6
#| fig-height: 3.5
#| fig-align: center

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"}

```{r}
#| eval: true
#| echo: true
#| fig-width: 6
#| fig-height: 3.5
#| fig-align: center

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"}

- This practice focuses on using an external library
    - We will chart each banks' earnings over time
- Do exercise 6 on the supplementary R practice file:
    - <a href="https://rmc.link/acct420r1sup">R Practice</a>
    - Short link: [rmc.link/acct420r1sup](https://rmc.link/acct420r1sup)

> 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"}

- `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"}

- `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"}

- 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"}

```{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"}

- 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="https://rmc.link/acct420r1sup">R Practice</a>
    - Short link: [rmc.link/acct420r1sup](https://rmc.link/acct420r1sup)






# End Matter {data-background-video="../Backgrounds/section.mp4"}

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

> 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" visibility="uncounted"}

- `{DT}`
- `{downlit}`
- `{kableExtra}`
- `{knitr}`
- `{plotly}`
- `{quantmod}`
- `{quarto}`
- `{revealjs}`
- `RColorBrewer`
- `{tidyverse}`

## Custom functions {data-background="../Backgrounds/code.jpg" visibility="uncounted"}

```{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]])
}
```




