---
title: "Session 1 R practice"
author: "Dr. Richard M. Crowley"
date: "ACCT 420, Fall 2018, Session 1"
output:
  html_document:
    theme: spacelab
    highlight: default
    toc: true
    toc_float:
      collapsed: false
    self_contained: false
---

```{r, include=FALSE}
tutorial::go_interactive()
```

## Data in R

To run your code, click *run*.  It will let you know if your code is correct or not, and will offer hints on what to fix if needed.  If you are stuck, you can see the solution by clicking *Solution*.


### Exercise 1: Vectors

```{r ex="create_a", type="pre-exercise-code"}
df <- read.csv(text="gvkey,datadate,fyear,tic,conm,at,dptc,lt,ni
3243,20101231,2010,C,CITIGROUP INC,1913902,844968,1748113,10602
3243,20111231,2011,C,CITIGROUP INC,1873878,865936,1694305,11067
3243,20121231,2012,C,CITIGROUP INC,1864660,930560,1673663,7541
3243,20131231,2013,C,CITIGROUP INC,1880382,968273,1674249,13673
3243,20141231,2014,C,CITIGROUP INC,1842530,899332,1630485,7313
3243,20151231,2015,C,CITIGROUP INC,1731210,907887,1508118,17242
3243,20161231,2016,C,CITIGROUP INC,1792077,929406,1565934,14912
3243,20171231,2017,C,CITIGROUP INC,1842465,959822,1640793,-6798
114628,20101231,2010,GS,GOLDMAN SACHS GROUP INC,911332,38569,833104,8354
114628,20111231,2011,GS,GOLDMAN SACHS GROUP INC,923225,46109,851396,4442
114628,20121231,2012,GS,GOLDMAN SACHS GROUP INC,938555,70124,862331,7475
114628,20131231,2013,GS,GOLDMAN SACHS GROUP INC,911507,70807,832714,8040
114628,20141231,2014,GS,GOLDMAN SACHS GROUP INC,856240,83008,773039,8477
114628,20151231,2015,GS,GOLDMAN SACHS GROUP INC,861395,97519,774208,6083
114628,20161231,2016,GS,GOLDMAN SACHS GROUP INC,860165,124098,772766,7398
114628,20171231,2017,GS,GOLDMAN SACHS GROUP INC,916776,138604,833980,4286
2968,20101231,2010,JPM,JPMORGAN CHASE & CO,2117605,930369,1941499,17370
2968,20111231,2011,JPM,JPMORGAN CHASE & CO,2265792,1127806,2082219,18976
2968,20121231,2012,JPM,JPMORGAN CHASE & CO,2359141,1193593,2155072,21284
2968,20131231,2013,JPM,JPMORGAN CHASE & CO,2415689,1287765,2204511,17923
2968,20141231,2014,JPM,JPMORGAN CHASE & CO,2573126,1363427,2341061,21762
2968,20151231,2015,JPM,JPMORGAN CHASE & CO,2351698,1279715,2104125,24442
2968,20161231,2016,JPM,JPMORGAN CHASE & CO,2490972,1375179,2236782,24733
2968,20171231,2017,JPM,JPMORGAN CHASE & CO,2533600,1443982,2277907,24441
", stringsAsFactors=FALSE)
library(dplyr)
library(magrittr)
earnings_JPM <- df %>% filter(tic=="JPM") %>% select(ni) %>% .$ni
earnings_GS <- df %>% filter(tic=="GS") %>% select(ni) %>% .$ni
earnings_C <- df %>% filter(tic=="C") %>% select(ni) %>% .$ni
```

```{r ex="create_a", type="sample-code"}
# Each vector below contains earnings information from 2010 through 2017
years <- c(2010:2017)
earnings_C  # Citigroup earnings, in millions of USD
earnings_GS  # Goldman Sachs earnings, in millions of USD

# Create a new vector, `Citi_minus_Goldman`, that contains the difference between Citibank's and Goldman Sach's earnings
Citi_minus_Goldman <- 

# Name the vector `Citi_minus_Goldman` with the `years` vector


# Create a new vector, `Citi_lower`, that contains TRUE for years where Citi
# Had lower earnings, and FALSE for other years. Use a conditional statement to determine this.
Citi_lower <- 
  
Citi_lower  # Prints the vector -- no need to change this line

# In how many years did Citi have lower earnings?  Use `sum()` to determine this.
Citi_lower_count <- 

Citi_lower_count  # Prints the number -- no need to change this line

#END
```

```{r ex="create_a", type="solution"}
# Each vector below contains earnings information from 2010 through 2017
years <- c(2010:2017)
earnings_C  # Citigroup earnings, in millions of USD
earnings_GS  # Goldman Sachs earnings, in millions of USD

# Create a new vector, `Citi_minus_Goldman`, that contains the difference between Citibank's and Goldman Sach's earnings
Citi_minus_Goldman <- earnings_C - earnings_GS

# Name the vector `Citi_minus_Goldman` with the `years` vector
names(Citi_minus_Goldman) <- years

# Create a new vector, `Citi_lower`, that contains TRUE for years where Citi
# Had lower earnings, and FALSE for other years. Use a conditional statement to determine this.
Citi_lower <- Citi_minus_Goldman < 0

Citi_lower  # Prints the vector -- no need to change this line

# In how many years did Citi have lower earnings?  Use `sum()` to determine this.
Citi_lower_count <- sum(Citi_lower)

Citi_lower  # Prints the vector -- no need to change this line

#END
```

```{r ex="create_a", type="sct"}
# Template based on https://www.rdocumentation.org/packages/testwhat/versions/4.1.1
# Check if something is explicitly typed
# test_student_typed('roa', not_typed_msg='')

# Check if function was used in input code
# test_function('c',incorrect_msg='')
test_function('names',incorrect_msg='You need to use the `names()` function to name the elements of `Citi_minus_Goldman`')
test_function('sum',incorrect_msg='You need to use the `sum()` function to determine the number of years that Citi had lower earnings than Goldman Sachs.`')

# Requires an object `x` to have the same value as the solution
test_object("Citi_minus_Goldman",incorrect_msg = "`Citi_minus_Goldman` should contain earnings for Citi *minus* earnings for Goldman Sachs for each year.  It should also be named with the `years` vector.",undefined_msg = "Did you define `Citi_minus_Goldman`?")
test_object("Citi_lower",incorrect_msg = "`Citi_lower` does not appear to be correct.",undefined_msg = "Did you define `Citi_lower`?")
test_object("Citi_lower_count",incorrect_msg = "`Citi_lower_count` does not appear to be correct.",undefined_msg = "Did you define `Citi_lower_count`?")

# Requires an onject with the same value of `x` in the solution
# test_an_object("x",undefined_msg="")

# Check if a vector of predefined objects are unchanged
# test_predefined_objects(c('x','y'),incorrect_msg="Don't onverwrite the predefined variables")

# Checks for a regex pattern in trhe output
# test_output_regex(pattern,fixed=F, times=1, incorrect_msg='')

# Can check an arbitrary expression across both solution and student code
#test_expression_output("typeof(company_name)", incorrect_msg="Did you store textual data in `company_name`?")

test_error()
success_msg("Awesome!")

# Other functions to note:
#     - test_or(a,b) -- checks if either test a or test b pass
#     - test_ggplot() -- can check if plots are correct
#     - test_function() -- can also check included parameters
#     - test_loop() -- checking for and while loops
#     - test_library_function('package', not_called_msg='',incorrect_msg='')
#     - test_if_else() -- checking if statements
#     - test_expression_error() -- can check if functions are properly defined
#     - test_operator('operator',), not_called_msg='',incorrect_msg='')
#     - test_function_definition() -- rigorously check defined function
#     - test_data_frame() -- check if dataframe [columns] are equivalent
#     - test_function_result, test_expression_result
```

### Exercise 2: Lists

```{r ex="create_c", type="pre-exercise-code"}
df <- read.csv(text="gvkey,datadate,fyear,tic,conm,at,dptc,lt,ni
3243,20101231,2010,C,CITIGROUP INC,1913902,844968,1748113,10602
3243,20111231,2011,C,CITIGROUP INC,1873878,865936,1694305,11067
3243,20121231,2012,C,CITIGROUP INC,1864660,930560,1673663,7541
3243,20131231,2013,C,CITIGROUP INC,1880382,968273,1674249,13673
3243,20141231,2014,C,CITIGROUP INC,1842530,899332,1630485,7313
3243,20151231,2015,C,CITIGROUP INC,1731210,907887,1508118,17242
3243,20161231,2016,C,CITIGROUP INC,1792077,929406,1565934,14912
3243,20171231,2017,C,CITIGROUP INC,1842465,959822,1640793,-6798
114628,20101231,2010,GS,GOLDMAN SACHS GROUP INC,911332,38569,833104,8354
114628,20111231,2011,GS,GOLDMAN SACHS GROUP INC,923225,46109,851396,4442
114628,20121231,2012,GS,GOLDMAN SACHS GROUP INC,938555,70124,862331,7475
114628,20131231,2013,GS,GOLDMAN SACHS GROUP INC,911507,70807,832714,8040
114628,20141231,2014,GS,GOLDMAN SACHS GROUP INC,856240,83008,773039,8477
114628,20151231,2015,GS,GOLDMAN SACHS GROUP INC,861395,97519,774208,6083
114628,20161231,2016,GS,GOLDMAN SACHS GROUP INC,860165,124098,772766,7398
114628,20171231,2017,GS,GOLDMAN SACHS GROUP INC,916776,138604,833980,4286
2968,20101231,2010,JPM,JPMORGAN CHASE & CO,2117605,930369,1941499,17370
2968,20111231,2011,JPM,JPMORGAN CHASE & CO,2265792,1127806,2082219,18976
2968,20121231,2012,JPM,JPMORGAN CHASE & CO,2359141,1193593,2155072,21284
2968,20131231,2013,JPM,JPMORGAN CHASE & CO,2415689,1287765,2204511,17923
2968,20141231,2014,JPM,JPMORGAN CHASE & CO,2573126,1363427,2341061,21762
2968,20151231,2015,JPM,JPMORGAN CHASE & CO,2351698,1279715,2104125,24442
2968,20161231,2016,JPM,JPMORGAN CHASE & CO,2490972,1375179,2236782,24733
2968,20171231,2017,JPM,JPMORGAN CHASE & CO,2533600,1443982,2277907,24441
", stringsAsFactors=FALSE)
library(dplyr)
library(magrittr)
df <- df %>%
  mutate(roa = ni/at,
         roa_lag = lag(roa))
model <- summary(lm(roa ~ roa_lag, data=df))
```

```{r ex="create_c", type="sample-code"}
# Below is a linear model of JPMorgan's, Citi's, and Goldman's ROA regressed on prior year ROA
model
str(model)

# Run the above and examine the output.
# Extract the r squared (not adjusted) from the model

#END
```

```{r ex="create_c", type="solution"}
# Below is a linear model of JPMorgan's, Citi's, and Goldman's ROA regressed on prior year ROA
model
str(model)

# Run the above and examine the output.
# Extract the r squared (not adjusted) from the model
model$r.squared
#END
```

```{r ex="create_c", type="sct"}
# Template based on https://www.rdocumentation.org/packages/testwhat/versions/4.1.1
# Check if something is explicitly typed
# test_student_typed('x <- 2', not_typed_msg='')

# Check if function was used in input code
# test_function('c',incorrect_msg='')  

# Requires an object `x` to have the same value as the solution
# test_object("x",incorrect_msg = "",undefined_msg = "")  

# Requires an onject with the same value of `x` in the solution
# test_an_object("x",undefined_msg="")

# Checks if output of student's code contains given evaluated expression
test_output_contains("model$r.squared",incorrect_msg = "You have not extracted and printed the right number!")

# Check if a vector of predefined objects are unchanged
# test_predefined_objects(c('x','y'),incorrect_msg="Don't onverwrite the predefined variables")

# Checks for a regex pattern in trhe output
# test_output_regex(pattern,fixed=F, times=1, incorrect_msg='')

# Can check an arbitrary expression across both solution and student code
# test_expression_output("typeof(company_name)", incorrect_msg="Did you store textual data in `company_name`?")

test_error()
success_msg("Awesome!")

# Other functions to note:
#     - test_or(a,b) -- checks if either test a or test b pass
#     - test_ggplot() -- can check if plots are correct
#     - test_function() -- can also check included parameters
#     - test_loop() -- checking for and while loops
#     - test_library_function('package', not_called_msg='',incorrect_msg='')
#     - test_if_else() -- checking if statements
#     - test_expression_error() -- can check if functions are properly defined
#     - test_operator('operator',), not_called_msg='',incorrect_msg='')
#     - test_function_definition() -- rigorously check defined function
#     - test_data_frame() -- check if dataframe [columns] are equivalent
#     - test_function_result, test_expression_result
```

### Exercise 3: Data frames



```{r ex="create_d", type="pre-exercise-code"}
df <- read.csv(text="gvkey,datadate,fyear,tic,conm,at,dptc,lt,ni
3243,20101231,2010,C,CITIGROUP INC,1913902,844968,1748113,10602
3243,20111231,2011,C,CITIGROUP INC,1873878,865936,1694305,11067
3243,20121231,2012,C,CITIGROUP INC,1864660,930560,1673663,7541
3243,20131231,2013,C,CITIGROUP INC,1880382,968273,1674249,13673
3243,20141231,2014,C,CITIGROUP INC,1842530,899332,1630485,7313
3243,20151231,2015,C,CITIGROUP INC,1731210,907887,1508118,17242
3243,20161231,2016,C,CITIGROUP INC,1792077,929406,1565934,14912
3243,20171231,2017,C,CITIGROUP INC,1842465,959822,1640793,-6798
114628,20101231,2010,GS,GOLDMAN SACHS GROUP INC,911332,38569,833104,8354
114628,20111231,2011,GS,GOLDMAN SACHS GROUP INC,923225,46109,851396,4442
114628,20121231,2012,GS,GOLDMAN SACHS GROUP INC,938555,70124,862331,7475
114628,20131231,2013,GS,GOLDMAN SACHS GROUP INC,911507,70807,832714,8040
114628,20141231,2014,GS,GOLDMAN SACHS GROUP INC,856240,83008,773039,8477
114628,20151231,2015,GS,GOLDMAN SACHS GROUP INC,861395,97519,774208,6083
114628,20161231,2016,GS,GOLDMAN SACHS GROUP INC,860165,124098,772766,7398
114628,20171231,2017,GS,GOLDMAN SACHS GROUP INC,916776,138604,833980,4286
2968,20101231,2010,JPM,JPMORGAN CHASE & CO,2117605,930369,1941499,17370
2968,20111231,2011,JPM,JPMORGAN CHASE & CO,2265792,1127806,2082219,18976
2968,20121231,2012,JPM,JPMORGAN CHASE & CO,2359141,1193593,2155072,21284
2968,20131231,2013,JPM,JPMORGAN CHASE & CO,2415689,1287765,2204511,17923
2968,20141231,2014,JPM,JPMORGAN CHASE & CO,2573126,1363427,2341061,21762
2968,20151231,2015,JPM,JPMORGAN CHASE & CO,2351698,1279715,2104125,24442
2968,20161231,2016,JPM,JPMORGAN CHASE & CO,2490972,1375179,2236782,24733
2968,20171231,2017,JPM,JPMORGAN CHASE & CO,2533600,1443982,2277907,24441
", stringsAsFactors=FALSE)
library(dplyr)
library(magrittr)
```

```{r ex="create_d", type="sample-code"}
# df contains 9 variables across 8 years and 3 banks
# dplyr (from tidyverse) is already loaded for you
head(df)

# Extract all rows about Citigroup, and store this in `df_C`.  Use dplyr's `filter()`.
df_C <- df %>%
  filter()

# Calculate the ratio of debt to assets for each firm-year.
# lt is the amount of liabilities the bank had
# at is the amount of assets the bank had
# Store this in a new column of the dataframe called "debt_ratio"
# Use dplyr's `mutate()` to calculate this
df <- df %>%
  mutate()

# What is the median of debt to assets across these firm years?  Use the median funtion to calculate this
median()

# Now, sort the dataframe to be increasing in debt_ratio.  Use dplyr's `arrange()` to accomplish this.
df_sorted <- df %>%
  arrange()


# Finished code for you:
# Which bank-year had the lowest debt ratio?
print(paste(df_sorted$fyear[1], df_sorted$conm[1],':',df_sorted$debt_ratio[1]))  # This line is finished already

# The highest debt ratio?
r <- nrow(df_sorted)
print(paste(df_sorted$fyear[r], df_sorted$conm[r],':',df_sorted$debt_ratio[r]))  # This line is finished already

#END
```

```{r ex="create_d", type="solution"}
# df contains 9 variables across 8 years and 3 banks
# dplyr (from tidyverse) is already loaded for you
head(df)

# Extract all rows about Citigroup, and store this in `df_C`.  Use dplyr's `filter()`.
df_C <- df %>%
  filter(tic == "C")

# Calculate the ratio of debt to assets for each firm-year.
# lt is the amount of liabilities the bank had
# at is the amount of assets the bank had
# Store this in a new column of the dataframe called "debt_ratio"
# Use dplyr's `mutate()` to calculate this
df <- df %>%
  mutate(debt_ratio = lt/at)

# What is the median of debt to assets across these firm years?  Use the median funtion to calculate this
median(df$debt_ratio)

# Now, sort the dataframe to be increasing in debt_ratio.  Use dplyr's `arrange()` to accomplish this.
df_sorted <- df %>%
  arrange(debt_ratio)


# Finished code for you:
# Which bank-year had the lowest debt ratio?
print(paste(df_sorted$fyear[1], df_sorted$conm[1],':',df_sorted$debt_ratio[1]))  # This line is finished already

# The highest debt ratio?
r <- nrow(df_sorted)
print(paste(df_sorted$fyear[r], df_sorted$conm[r],':',df_sorted$debt_ratio[r]))  # This line is finished already

#END
```

```{r ex="create_d", type="sct"}
# Template based on https://www.rdocumentation.org/packages/testwhat/versions/4.1.1
# Check if something is explicitly typed
# test_student_typed('x <- 2', not_typed_msg='')
test_expression_output("df_C",incorrect_msg = "Remember to filter for Citibank's rows and store them in `df_C`.")
test_expression_output("sum(df$debt_ratio)",incorrect_msg = "Remember to calculate `debt_ratio` and add it to the dataframe.")
test_function('median',incorrect_msg='Did you use `median()` to calculate the average ratio?')
test_expression_output("median(df$debt_ratio)",incorrect_msg = "Did you output the median of `ratio`?")
test_expression_output("df_sorted$debt_ratio[1]",incorrect_msg = "Make sure to sort by `debt_ratio`.")
test_error()
success_msg("Awesome!")

# Check if function was used in input code


# Requires an object `x` to have the same value as the solution


# Requires an onject with the same value of `x` in the solution
# test_an_object("x",undefined_msg="")

# Checks if output of student's code contains given evaluated expression

# Check if a vector of predefined objects are unchanged
# test_predefined_objects(c('x','y'),incorrect_msg="Don't onverwrite the predefined variables")

# Checks for a regex pattern in trhe output
# test_output_regex(pattern,fixed=F, times=1, incorrect_msg='')

# Can check an arbitrary expression across both solution and student code
# test_expression_output("typeof(company_name)", incorrect_msg="Did you store textual data in `company_name`?")



# Other functions to note:
#     - test_or(a,b) -- checks if either test a or test b pass
#     - test_ggplot() -- can check if plots are correct
#     - test_function() -- can also check included parameters
#     - test_loop() -- checking for and while loops
#     - test_library_function('package', not_called_msg='',incorrect_msg='')
#     - test_if_else() -- checking if statements
#     - test_expression_error() -- can check if functions are properly defined
#     - test_operator('operator',), not_called_msg='',incorrect_msg='')
#     - test_function_definition() -- rigorously check defined function
#     - test_data_frame() -- check if dataframe [columns] are equivalent
#     - test_function_result, test_expression_result
```

### Exercise 4: External library usage

Click the *expand* button to see the plot more clearly (note: may be blocked by pop-up blockers)

Note: If a plot displays, you have the right code.  The plot overrides the confirmation message.

```{r ex="create_h", type="pre-exercise-code"}
df <- read.csv(text="gvkey,datadate,fyear,tic,conm,at,dptc,lt,ni
3243,20101231,2010,C,CITIGROUP INC,1913902,844968,1748113,10602
3243,20111231,2011,C,CITIGROUP INC,1873878,865936,1694305,11067
3243,20121231,2012,C,CITIGROUP INC,1864660,930560,1673663,7541
3243,20131231,2013,C,CITIGROUP INC,1880382,968273,1674249,13673
3243,20141231,2014,C,CITIGROUP INC,1842530,899332,1630485,7313
3243,20151231,2015,C,CITIGROUP INC,1731210,907887,1508118,17242
3243,20161231,2016,C,CITIGROUP INC,1792077,929406,1565934,14912
3243,20171231,2017,C,CITIGROUP INC,1842465,959822,1640793,-6798
114628,20101231,2010,GS,GOLDMAN SACHS GROUP INC,911332,38569,833104,8354
114628,20111231,2011,GS,GOLDMAN SACHS GROUP INC,923225,46109,851396,4442
114628,20121231,2012,GS,GOLDMAN SACHS GROUP INC,938555,70124,862331,7475
114628,20131231,2013,GS,GOLDMAN SACHS GROUP INC,911507,70807,832714,8040
114628,20141231,2014,GS,GOLDMAN SACHS GROUP INC,856240,83008,773039,8477
114628,20151231,2015,GS,GOLDMAN SACHS GROUP INC,861395,97519,774208,6083
114628,20161231,2016,GS,GOLDMAN SACHS GROUP INC,860165,124098,772766,7398
114628,20171231,2017,GS,GOLDMAN SACHS GROUP INC,916776,138604,833980,4286
2968,20101231,2010,JPM,JPMORGAN CHASE & CO,2117605,930369,1941499,17370
2968,20111231,2011,JPM,JPMORGAN CHASE & CO,2265792,1127806,2082219,18976
2968,20121231,2012,JPM,JPMORGAN CHASE & CO,2359141,1193593,2155072,21284
2968,20131231,2013,JPM,JPMORGAN CHASE & CO,2415689,1287765,2204511,17923
2968,20141231,2014,JPM,JPMORGAN CHASE & CO,2573126,1363427,2341061,21762
2968,20151231,2015,JPM,JPMORGAN CHASE & CO,2351698,1279715,2104125,24442
2968,20161231,2016,JPM,JPMORGAN CHASE & CO,2490972,1375179,2236782,24733
2968,20171231,2017,JPM,JPMORGAN CHASE & CO,2533600,1443982,2277907,24441
", stringsAsFactors=FALSE)
df$debt_ratio = df$lt / df$at
```

```{r ex="create_h", type="sample-code"}
# df is the same dataframe from Exercise #3

# To use `ggplot()` below, we need to load the `ggplot2` package
# Load the package here


# Plots the three banks' net income by fiscal year
# Try changing the variables and explore the data!
ggplot(df, aes(x=fyear, y=debt_ratio)) + geom_line() + facet_wrap(~tic) # This code is complete already

#END
```

```{r ex="create_h", type="solution"}
# df is the same dataframe from Exercise #3

# To use `ggplot()` below, we need to load the `ggplot2` package
# Load the package here
library(ggplot2)

# Plots the three banks' net income by fiscal year
# Try changing the variables and explore the data!
ggplot(df, aes(x=fyear, y=debt_ratio)) + geom_line() + facet_wrap(~tic) # This code is complete already

#END
```

```{r ex="create_h", type="sct"}

test_function('library',incorrect_msg='Use library to load the `ggplot2` package.')
test_student_typed('library(ggplot2)', not_typed_msg='Make sure you load the `ggplot2` package!')

# Template based on https://www.rdocumentation.org/packages/testwhat/versions/4.1.1
# Check if something is explicitly typed
# test_student_typed('library(lattice)', not_typed_msg='Make sure you load the package')

# Check if function was used in input code
# test_function('c',incorrect_msg='')  

# Requires an object `x` to have the same value as the solution
# test_object("x",incorrect_msg = "",undefined_msg = "")  

# Requires an onject with the same value of `x` in the solution
# test_an_object("x",undefined_msg="")

# Checks if output of student's code contains given evaluated expression
# test_output_contains("x",incorrect_msg = "")

# Check if a vector of predefined objects are unchanged
# test_predefined_objects(c('x','y'),incorrect_msg="Don't onverwrite the predefined variables")

# Checks for a regex pattern in trhe output
# test_output_regex(pattern,fixed=F, times=1, incorrect_msg='')

# Can check an arbitrary expression across both solution and student code
# test_expression_output("typeof(company_name)", incorrect_msg="Did you store textual data in `company_name`?")

test_error()
success_msg("Awesome!")

# Other functions to note:
#     - test_or(a,b) -- checks if either test a or test b pass
#     - test_ggplot() -- can check if plots are correct
#     - test_function() -- can also check included parameters
#     - test_loop() -- checking for and while loops
#     - test_library_function('package', not_called_msg='',incorrect_msg='')
#     - test_if_else() -- checking if statements
#     - test_expression_error() -- can check if functions are properly defined
#     - test_operator('operator',), not_called_msg='',incorrect_msg='')
#     - test_function_definition() -- rigorously check defined function
#     - test_data_frame() -- check if dataframe [columns] are equivalent
#     - test_function_result, test_expression_result
```

### Exercise 5: Making your own function

```{r ex="create_i", type="pre-exercise-code"}
df <- read.csv(text="gvkey,datadate,fyear,tic,conm,at,dptc,lt,ni
3243,20101231,2010,C,CITIGROUP INC,1913902,844968,1748113,10602
3243,20111231,2011,C,CITIGROUP INC,1873878,865936,1694305,11067
3243,20121231,2012,C,CITIGROUP INC,1864660,930560,1673663,7541
3243,20131231,2013,C,CITIGROUP INC,1880382,968273,1674249,13673
3243,20141231,2014,C,CITIGROUP INC,1842530,899332,1630485,7313
3243,20151231,2015,C,CITIGROUP INC,1731210,907887,1508118,17242
3243,20161231,2016,C,CITIGROUP INC,1792077,929406,1565934,14912
3243,20171231,2017,C,CITIGROUP INC,1842465,959822,1640793,-6798
114628,20101231,2010,GS,GOLDMAN SACHS GROUP INC,911332,38569,833104,8354
114628,20111231,2011,GS,GOLDMAN SACHS GROUP INC,923225,46109,851396,4442
114628,20121231,2012,GS,GOLDMAN SACHS GROUP INC,938555,70124,862331,7475
114628,20131231,2013,GS,GOLDMAN SACHS GROUP INC,911507,70807,832714,8040
114628,20141231,2014,GS,GOLDMAN SACHS GROUP INC,856240,83008,773039,8477
114628,20151231,2015,GS,GOLDMAN SACHS GROUP INC,861395,97519,774208,6083
114628,20161231,2016,GS,GOLDMAN SACHS GROUP INC,860165,124098,772766,7398
114628,20171231,2017,GS,GOLDMAN SACHS GROUP INC,916776,138604,833980,4286
2968,20101231,2010,JPM,JPMORGAN CHASE & CO,2117605,930369,1941499,17370
2968,20111231,2011,JPM,JPMORGAN CHASE & CO,2265792,1127806,2082219,18976
2968,20121231,2012,JPM,JPMORGAN CHASE & CO,2359141,1193593,2155072,21284
2968,20131231,2013,JPM,JPMORGAN CHASE & CO,2415689,1287765,2204511,17923
2968,20141231,2014,JPM,JPMORGAN CHASE & CO,2573126,1363427,2341061,21762
2968,20151231,2015,JPM,JPMORGAN CHASE & CO,2351698,1279715,2104125,24442
2968,20161231,2016,JPM,JPMORGAN CHASE & CO,2490972,1375179,2236782,24733
2968,20171231,2017,JPM,JPMORGAN CHASE & CO,2533600,1443982,2277907,24441
", stringsAsFactors=FALSE)
df2 <- read.csv(text="gvkey,datadate,fyear,tic,conm,at,dptc,lt,ni
3243,20101231,2010,C,CITIGROUP INC,1913902,844968,1748113,10602
3243,20111231,2011,C,CITIGROUP INC,1873878,865936,1694305,11067
3243,20121231,2012,C,CITIGROUP INC,1864660,930560,1673663,7541
3243,20131231,2013,C,CITIGROUP INC,1880382,968273,1674249,13673
3243,20141231,2014,C,CITIGROUP INC,1842530,899332,1630485,7313
3243,20151231,2015,C,CITIGROUP INC,1731210,907887,1508118,17242
3243,20161231,2016,C,CITIGROUP INC,1792077,929406,1565934,14912
3243,20171231,2017,C,CITIGROUP INC,1842465,959822,1640793,-6798
114628,20101231,2010,GS,GOLDMAN SACHS GROUP INC,911332,38569,833104,8354
114628,20111231,2011,GS,GOLDMAN SACHS GROUP INC,923225,46109,851396,4442
114628,20121231,2012,GS,GOLDMAN SACHS GROUP INC,938555,70124,862331,7475
114628,20131231,2013,GS,GOLDMAN SACHS GROUP INC,911507,70807,832714,8040
114628,20141231,2014,GS,GOLDMAN SACHS GROUP INC,856240,83008,773039,8477
114628,20151231,2015,GS,GOLDMAN SACHS GROUP INC,861395,97519,774208,6083
114628,20161231,2016,GS,GOLDMAN SACHS GROUP INC,860165,124098,772766,7398
114628,20171231,2017,GS,GOLDMAN SACHS GROUP INC,916776,138604,833980,4286", stringsAsFactors=FALSE)
library(dplyr)
library(magrittr)
```

```{r ex="create_i", type="sample-code"}
# Design a function (using function()) that finds the largest bank from the dataframe that we have been using.  Here, largest means most assets in any year.
# The function should take `df` as its argument, and should output the bank name.  The name should be of the bank that had the highest total assets of any (bank, year) pairs.
# `dplyr` and `magrittr` are already loaded, for convenience.  You can solve this with or without these packages.

biggest_bank <- 

# Now, let's test the function you created
biggest_bank(df)

#END
```

```{r ex="create_i", type="solution"}
# Design a function (using function()) that finds the largest bank from the dataframe that we have been using.  Here, largest means most assets in any year.
# The function should take `df` as its argument, and should output the bank name.  The name should be of the bank that had the highest total assets of any (bank, year) pairs.  Name is stored in that data as `conm`.
# `dplyr` and `magrittr` are already loaded, for convenience.  You can solve this with or without these packages.

head(df)

# This is a simple way to do this using `dplyr` and `magrittr`.
# There are many other solutions
biggest_bank <- function(df) {
  df %>%
    arrange(-at) %>%
    slice(1) %>%
    .$conm
}

# Another possible solution would be:
# biggest_bank <- function(df) {
#   m <- max(df$at)
#   df$conm[which(df$at == m)]
# }

# Now, let's test the function you created
biggest_bank(df)

#END
```

```{r ex="create_i", type="sct"}

test_expression_output("biggest_bank(df)", incorrect_msg="It appears that your function doesn't output the right bank.")
test_expression_output("biggest_bank(df2)", incorrect_msg="It appears that your function doesn't output the correct answer on other data.")

# Template based on https://www.rdocumentation.org/packages/testwhat/versions/4.1.1
# Check if something is explicitly typed
# test_student_typed('x <- 2', not_typed_msg='')

# Check if function was used in input code
# test_function('c',incorrect_msg='')  

# Requires an object `x` to have the same value as the solution
# test_object("x",incorrect_msg = "",undefined_msg = "")  

# Requires an onject with the same value of `x` in the solution
# test_an_object("x",undefined_msg="")

# Checks if output of student's code contains given evaluated expression
# test_output_contains("x",incorrect_msg = "")

# Check if a vector of predefined objects are unchanged
# test_predefined_objects(c('x','y'),incorrect_msg="Don't onverwrite the predefined variables")

# Checks for a regex pattern in trhe output
# test_output_regex(pattern,fixed=F, times=1, incorrect_msg='')

# Can check an arbitrary expression across both solution and student code
# test_expression_output("typeof(company_name)", incorrect_msg="Did you store textual data in `company_name`?")

test_error()
success_msg("Awesome!")

# Other functions to note:
#     - test_or(a,b) -- checks if either test a or test b pass
#     - test_ggplot() -- can check if plots are correct
#     - test_function() -- can also check included parameters
#     - test_loop() -- checking for and while loops
#     - test_library_function('package', not_called_msg='',incorrect_msg='')
#     - test_if_else() -- checking if statements
#     - test_expression_error() -- can check if functions are properly defined
#     - test_operator('operator',), not_called_msg='',incorrect_msg='')
#     - test_function_definition() -- rigorously check defined function
#     - test_data_frame() -- check if dataframe [columns] are equivalent
#     - test_function_result, test_expression_result
```
