---
title: "R Supplement practice"
author: "Dr. Richard M. Crowley"
date: "ACCT 420, Fall 2021, R Supplement"
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: Arithmetic

```{r ex="create_j", type="pre-exercise-code"}
# no pec
```

```{r ex="create_j", type="sample-code"}
# Pick a company and assign it's name to company_name
company_name <- 

# Assign a boolean value to is_tech_firm
is_tech_firm <- 

# Assign a numeric value to revenue
revenue <- 

# Assign a description of the firm to company_desc
company_desc <- ""

#END
```

```{r ex="create_j", type="solution"}
# Assign a character value to company_name
company_name <- "Google"

# Assign a boolean value to is_tech_firm
is_tech_firm <- TRUE

# Assign a numeric value to revenue
revenue <- 40000

# Assign a description of the firm to company_desc
company_desc <- "Started with search, but is now everywhere"

#END
```

```{r ex="create_j", 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 object 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_expression_output("typeof(is_tech_firm)", incorrect_msg="Did you store TRUE or FALSE in `is_tech_firm`?")
test_expression_output("typeof(revenue)", incorrect_msg="Did you store numeric data in `revenue`?")
test_expression_output("typeof(company_desc)", incorrect_msg="Did you store textual data in `company_desc`?")

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: Data types

```{r ex="create_b", type="pre-exercise-code"}
# no pec
```

```{r ex="create_b", type="sample-code"}
# Pick a company and assign it's name to company_name
company_name <- 

# Assign a boolean value to is_tech_firm
is_tech_firm <- 

# Assign a numeric value to revenue
revenue <- 

# Assign a description of the firm to company_desc
company_desc <- ""

#END
```

```{r ex="create_b", type="solution"}
# Assign a character value to company_name
company_name <- "Google"

# Assign a boolean value to is_tech_firm
is_tech_firm <- TRUE

# Assign a numeric value to revenue
revenue <- 40000

# Assign a description of the firm to company_desc
company_desc <- "Started with search, but is now everywhere"

#END
```

```{r ex="create_b", 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("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_expression_output("typeof(is_tech_firm)", incorrect_msg="Did you store TRUE or FALSE in `is_tech_firm`?")
test_expression_output("typeof(revenue)", incorrect_msg="Did you store numeric data in `revenue`?")
test_expression_output("typeof(company_desc)", incorrect_msg="Did you store textual data in `company_desc`?")

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: Vectors

```{r ex="create_a", type="pre-exercise-code"}
earnings_B <- c(4.286, 24.441, -6.798)
assets <- c(916776, 2533600, 1842465)
```

```{r ex="create_a", type="sample-code"}
# Each vector below contains information about: Goldman Sachs, JPMorgan, and Citigroup
earnings_B  # In billions of USD
assets  # In millions of USD

# create a new vector, earnings, that contains these firms earnings in Millions
earnings <- 

# Create a vector of names for the three banks (any understandable name is fine)
bank_names <- 

# Calculate ROA and store into the roa vector
roa <- 

# Apply names to roa


# Output the ROA vector to see the banks' 2017 ROA


#END
```

```{r ex="create_a", type="solution"}
# Each vector below contains information about: Goldman Sachs, JPMorgan, and Citigroup
earnings_B  # In billions of USD
assets  # In millions of USD

# create a new vector, earnings, that contains these firms earnings in Millions
earnings <- earnings_B * 1000

# Create a vector of names for the three banks (any understandable name is fine)
bank_names <- c("Goldman", "JPMorgan", "Citigroup")

# Calculate ROA and store into the roa vector
roa <- earnings / assets

# Apply names to roa
names(roa) <- bank_names

# Output the ROA vector to see the banks' 2017 ROA
roa

#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("c",incorrect_msg="You need to use the `c` function to store the banks\' names")
test_function('names',incorrect_msg='You need to use the `names()` function to name the elements of `roa`')

# Requires an object `x` to have the same value as the solution
test_object("earnings",incorrect_msg = "Make sure to convert `earnings_B` from billions to millions of USD",undefined_msg = "Did you define `earnings`?")
test_object("roa",incorrect_msg = "Did you correctly calculate roa?",undefined_msg = "Did you define `roa`?")

# 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("roa",incorrect_msg = "Did you remember to print `roa`?")

# 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 4: Lists



```{r ex="create_c", type="pre-exercise-code"}
df <- data.frame(year=c(2010,2011,2012,2013,2014,2015,2016,2017),
                 assets=c(930369,1127806,1193593,1287765,1363427,1279715,1375179,1443982),
                 deposits=c(2117605,2265792,2359141,2415689,2573126,2351698,2490972,2533600))
model <- summary(lm(assets ~ deposits, data=df))
```

```{r ex="create_c", type="sample-code"}
# Below is a linear model of JPMorgan's assets regressed on customer's total deposits
model
str(model)

# Run the above and examine the output.
# Extract the coefficient (Estimate) for deposits

#END
```

```{r ex="create_c", type="solution"}
# Below is a linear model of JPMorgan's assets regressed on customer's total deposits
model
str(model)

# Run the above and examine the output.
# Extract the coefficient (Estimate) for deposits and output it to console
# Do this using extraction with lists
model$coefficients[[2,1]]
```

```{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$coefficients[[2,1]]",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 5a: 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)
```

```{r ex="create_d", type="sample-code"}
# df contains 9 variables across 8 years and 3 banks
head(df)

# Extract the 8th row of the dataframe (Citigroup in 2017), using square brackets


# Calculate the ratio of deposits to assets for each firm-year.
# dptc is the amount of deposits held by the bank
# at is the amount of assets the bank had
# Store this in a new column of the dataframe called "ratio"


# What is the average (mean) of ratio?  Use the mean funtion to calculate this
mean()

# Now, sort the dataframe by ratio.  Finish the given command
ordering <- order()
df_sorted <- df[ordering,]  # This line is finished already


# Lastly, which bank-year had the lowest ratio?
print(paste(df_sorted$fyear[1], df_sorted$conm[1],':',df_sorted$ratio[1]))  # This line is finished already


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

#END
```

```{r ex="create_d", type="solution"}
# df contains 9 variables across 8 years and 3 banks
head(df)

# Extract the 8th row of the dataframe (Citigroup in 2017), using square brackets
df[8,]

# Calculate the ratio of deposits to assets for each firm-year.
# dptc is the amount of deposits held by the bank
# at is the amount of assets the bank had
# Store this in a new column of the dataframe called "ratio"
df$ratio = df$dptc / df$at

# What is the average (mean) of ratio?  Use the mean funtion to calculate this
mean(df$ratio)

# Now, sort the dataframe by ratio.  Finish the given command
ordering <- order(df$ratio)
df_sorted <- df[ordering,]  # This line is finished already


# Lastly, which bank-year had the lowest ratio?
print(paste(df_sorted$fyear[1], df_sorted$conm[1],':',df_sorted$ratio[1]))  # This line is finished already

# The highest ratio?
r <- nrow(df_sorted)
print(paste(df_sorted$fyear[r], df_sorted$conm[r],':',df_sorted$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_student_typed("df[8,]",not_typed_msg = "Make sure to output the 8th row of the data frame.")
test_expression_output("sum(df$ratio)",incorrect_msg = "Remember to calculate `ratio` and add it to the dataframe.")
test_function('mean',incorrect_msg='Did you use `mean()` to calculate the average ratio?')
test_output_contains("mean(df$ratio)",incorrect_msg = "Did you output the mean of `ratio`?")
test_expression_output("df_sorted$ratio[1]",incorrect_msg = "Make sure to sort by `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 5: Subsetting our data frame

```{r ex="create_e", 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)
```

```{r ex="create_e", type="sample-code"}
# df is the same dataframe from Exercise #4
head(df)

# Make a new dataframe, df_jpm, which only contains JPMorgan data
df_jpm <- 

# Make a new dataframe, df_midyears, which only contains data from 2012 through 2015
df_midyears <- 

# Make a new dataframe, df_loss, that only contains data where the banks had negative earnings
df_loss <-

#print out firm years with losses
print(paste(df_loss$fyear, df_loss$conm, df_loss$ni))  # This line is finished already

#END
```

```{r ex="create_e", type="solution"}
# df is the same dataframe from Exercise #4
head(df)

# Make a new dataframe, df_jpm, which only contains JPMorgan data
df_jpm <- df[df$tic == 'JPM',]

# Make a new dataframe, df_midyears, which only contains data from fiscal years 2012 through 2015
# Note: fiscal year is df$fyear in the data frame
df_midyears <- df[df$fyear > 2011 & df$fyear < 2016,]

# Make a new dataframe, df_loss, that only contains data where the banks had negative earnings
df_loss <- df[df$ni < 0,]

#print out firm years with losses
print(paste(df_loss$fyear, df_loss$conm, df_loss$ni))  # This line is finished already

#END
```

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

test_expression_output("sum(df_jpm$ni)", incorrect_msg="Did you make sure to only include all JPMorgan data in `df_jpm`?")
test_expression_output("sum(df_midyears$ni)", incorrect_msg="Did you make sure to remove both early and late years for `df_midyears`?")
test_expression_output("sum(df_loss$ni)", incorrect_msg="Did you filter on `ni` for `df_loss`?")


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

### Exercise 6: External library usage

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

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

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

# To use xyplot below, we need to load the "lattice" package
# Load the package here


# Plots the three banks' net income by fiscal year
# Try changing the variables and explore the data!
xyplot(ni~fyear | tic, data=df, type="l") # This code is complete already

#END
```

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

# To use xyplot below, we need to load the "lattice" package
# Load the package here
library(lattice)

# Plots the three banks' net income by fiscal year
# Try changing the variables and explore the data!
xyplot(ni~fyear | tic, data=df, type="l") # This code is complete already

#END
```

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

test_function('library',incorrect_msg='Use library to load the `lattice` package.')
test_student_typed('library(lattice)', not_typed_msg='Make sure you load the `lattice` 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 7: 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)
```

```{r ex="create_i", type="sample-code"}
# Designing a function (using function()) that converts USD to SGD
# Assume that the excahnge rate is 1.36
# NOTE: we could actually pull the exchange rate from the web, but datacamp doesn't support
#       such a function.  See the slide end notes for an example that does this!

convert_currency <- 

# Now, let's test the function you created
# Check the price of 1 USD in SGD
convert_currency(1)

# Check the highest amount of assets of any of our 3 banks, in SGD
max(convert_currency(df$at))

#END
```

```{r ex="create_i", type="solution"}
# Designing a function (using function()) that converts USD to SGD
# Assume that the excahnge rate is 1.36
# NOTE: we could actually pull the exchange rate from the web, but Datacamp doesn't support
#       such a function.  See the slide end notes for an example that does this!

convert_currency <- function(amount) {
  amount * 1.36
}

# Now, let's test the function you created
# Check the price of 1 USD in SGD
convert_currency(1)

# Check the highest amount of assets of any of our 3 banks, in SGD
max(convert_currency(df$at))

#END
```

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

test_student_typed('*1.36', not_typed_msg='Did you use an exchange rate of 1.36?')
test_expression_output("convert_currency(1)", incorrect_msg="It appears that your currency converter is not correct.")

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