---
title: "Session 2 R practice"
author: "Dr. Richard M. Crowley"
date: "ACCT 420, Session 2"
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: Using mutate() and lag()

```{r ex="create_a", type="pre-exercise-code"}
library(dplyr) # loads dplyr for data manipulation
df <- data.frame(company=c("UOL Group", "UOL Group", "UOL Group"),
                 year=c(2010, 2011, 2012),
                 revenue=c(1295, 1960, 1146),
                 assets=c(7939, 8524, 9564),
                 earnings=c(746, 664, 808))
df <- df %>%
  mutate(roa=earnings/assets)
```

```{r ex="create_a", type="sample-code"}
# The dataframe below contains historical earnings, revenue, assets,
# and roa for 3 years (2010, 2011, and 2012) and 3 firms.
df

# dplyr is already loaded

# Calculate the return on assets 1 year ago, using mutate and lag.
# Store the result in a data frame column named roa_lag.


#END
```

```{r ex="create_a", type="solution"}
# The dataframe below contains historical earnings, revenue, assets,
# and roa for 3 years (2010, 2011, and 2012) and 3 firms.
df

# dplyr is already loaded

# Calculate the return on assets 1 year ago, using mutate and lag.
# Store the result in a data frame column named roa_lag.
df <- df %>% 
  mutate(roa_lag=lag(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_expression_output("'roa_lag' %in% colnames(df)", incorrect_msg="Did you remember to save the output to the dataframe, and to name the column `roa_lag`?")
test_expression_output("df$roa_lag[1]", incorrect_msg="It looks like the calculation is wrong.")
test_expression_output("df$roa_lag[2]", incorrect_msg="It looks like the calculation is wrong.")
test_expression_output("df$roa_lag", incorrect_msg="It looks like your calculation is wrong -- you have the first 2 entries of the column correct though.")
test_student_typed('mutate(',not_typed_msg='Your result is correct, but it looks like you didn\'t use `mutate` to calculate it.')
test_student_typed('lag(',not_typed_msg='Your result is correct, but it looks like you didn\'t use `lag` to calculate it.')

# 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 2: Using mutate(), lead(), and group_by()

```{r ex="create_b", type="pre-exercise-code"}
library(dplyr) # loads dplyr for data manipulation
df <- data.frame(company=c("UOL Group", "UOL Group", "UOL Group", "United Engineers Ltd", "United Engineers Ltd", "United Engineers Ltd", "Top Global Ltd", "Top Global Ltd", "Top Global Ltd"),
                 year=c(2010, 2011, 2012, 2010, 2011, 2012, 2010, 2011, 2012),
                 revenue=c(1295, 1960, 1146, 901, 1187, 595, 4.5, 4.8, 5.5),
                 assets=c(7939, 8524, 9564, 2410, 3080, 3451, 109, 125, 295),
                 earnings=c(746, 664, 808, 186, 269, 72, -7.5, 16, 16))
df <- df %>%
  mutate(roa=earnings/assets)
```

```{r ex="create_b", type="sample-code"}
# The dataframe below contains historical earnings, revenue, assets,
# and roa for 3 years (2010, 2011, and 2012) and 3 firms.
df

# dplyr is already loaded

# Calculate the return on assets 1 year ahead, using group_by, mutate, lead, and ungroup.
# Store the result in a data frame column named roa_lead.


#END
```

```{r ex="create_b", type="solution"}
# The dataframe below contains historical earnings, revenue, assets,
# and roa for 3 years (2010, 2011, and 2012) and 3 firms.
df

# dplyr is already loaded

# Calculate the return on assets 1 year ahead, using group_by, mutate, lead, and ungroup.
# Store the result in a data frame column named roa_lead.
df <- df %>% 
  group_by(company) %>%
  mutate(roa_lead=lead(roa)) %>%
  ungroup()

#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_expression_output("'roa_lead' %in% colnames(df)", incorrect_msg="Did you remember to save the output to the dataframe, and to name the column `roa_lead`?")
test_expression_output("df$roa_lead[1]", incorrect_msg="It looks like the calculation is wrong.")
test_expression_output("df$roa_lead[2]", incorrect_msg="It looks like the calculation is wrong.")
test_expression_output("df$roa_lead[3]", incorrect_msg="Make sure to appropriately group the data -- use `group_by()` applied to `company`.")
test_expression_output("df$roa_lead", incorrect_msg="It looks like your calculation is wrong -- you have the first 3 entries of the column correct though.")
test_student_typed('group_by(',not_typed_msg='Your result is correct, but it looks like you didn\'t use `group_by` to calculate it.')
test_student_typed('mutate(',not_typed_msg='Your result is correct, but it looks like you didn\'t use `mutate` to calculate it.')
test_student_typed('lead(',not_typed_msg='Your result is correct, but it looks like you didn\'t use `lead` to calculate it.')
test_student_typed('ungroup(',not_typed_msg='Your result is correct, but it looks like you didn\'t ungroup the data after the calculation.')

# 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 3: Using mutate(), lag(), and group_by()

Note: Asset turnover is:
$$
Asset~Turnover_t = \frac{Revenue_t}{\frac{1}{2}(Assets_t + Assets_{t-1})}
$$

```{r ex="create_c", type="pre-exercise-code"}
library(dplyr) # loads dplyr for data manipulation
df <- data.frame(company=c("UOL Group", "UOL Group", "UOL Group", "United Engineers Ltd", "United Engineers Ltd", "United Engineers Ltd", "Top Global Ltd", "Top Global Ltd", "Top Global Ltd"),
                 year=c(2010, 2011, 2012, 2010, 2011, 2012, 2010, 2011, 2012),
                 revenue=c(1295, 1960, 1146, 901, 1187, 595, 4.5, 4.8, 5.5),
                 assets=c(7939, 8524, 9564, 2410, 3080, 3451, 109, 125, 295),
                 earnings=c(746, 664, 808, 186, 269, 72, -7.5, 16, 16))
df <- df %>%
  mutate(roa=earnings/assets)
df <- df %>% 
  group_by(company) %>%
  mutate(roa_lead=lead(roa)) %>%
  ungroup()
```

```{r ex="create_c", type="sample-code"}
# The dataframe below contains historical earnings, revenue, assets,
# and roa for 3 years (2010, 2011, and 2012) and 3 firms.
# It also contains roa_lead from the first exercise.
df

# dplyr is already loaded

# Calculate the asset turnover, using group_by, mutate, lag, and ungroup.
# The formula for asset turnover is given above
# Store the result in a data frame column named turnover.


#END
```

```{r ex="create_c", type="solution"}
# The dataframe below contains historical earnings, revenue, assets,
# and roa for 3 years (2010, 2011, and 2012) and 3 firms.
# It also contains roa_lead from the first exercise.
df

# dplyr is already loaded

# Calculate the asset turnover, using group_by, mutate, lag, and ungroup.
# The formula for asset turnover is given above
# Store the result in a data frame column named turnover.
df <- df %>% 
  group_by(company) %>%
  mutate(turnover=revenue / (0.5 * (assets+lag(assets)))) %>%
  ungroup()

#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_expression_output("'turnover' %in% colnames(df)", incorrect_msg="Did you remember to save the output to the dataframe, and to name the column `turnover`?")
test_expression_output("df$turnover[2]", incorrect_msg="It looks like the calculation is wrong.")
test_expression_output("df$turnover[3]", incorrect_msg="It looks like the calculation is wrong.")
test_expression_output("df$turnover[4]", incorrect_msg="Make sure to appropriately group the data -- use `group_by()` applied to `company`.")
test_expression_output("df$turnover", incorrect_msg="It looks like your calculation is wrong -- you have entries 2, 3 and 4 of the column correct though.")
test_student_typed('group_by(',not_typed_msg='Your result is correct, but it looks like you didn\'t use `group_by` to calculate it.')
test_student_typed('mutate(',not_typed_msg='Your result is correct, but it looks like you didn\'t use `mutate` to calculate it.')
test_student_typed('lag(',not_typed_msg='Your result is correct, but it looks like you didn\'t use `lag` to calculate it.')
test_student_typed('ungroup(',not_typed_msg='Your result is correct, but it looks like you didn\'t ungroup the data after the calculation.')

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

