---
title: "Week 2 R Style and Programming: Exercises"
date: "January 18, 2018"
output: html_document
---


```{r setup, include=FALSE}
library(knitr)
knitr::opts_chunk$set(echo = TRUE)
knitr::knit_hooks$set(mysize = function(before, options, envir) {
  if (before) 
    return(options$size)
})
```

## Exercise: Order of operations
Note that order of operations is important in writing R code.
```{r opt,eval=F}
4 - 2 ^ 2
(4 - 2) ^ 2
5 * 2 - 3 ^ 2
! TRUE & pi == 3
! (TRUE | FALSE) 
```

Evaluate all four expressions. Note `!` is R's not operator.

## Exercise: Function Descriptions 
Document this function with 

1. a description,
2. summary of input(s)
3. summary of outputs

```{r}
RollDice <- function(num.rolls){
  # 
  # ARGS:
  # RETURNS: 
  return(sample(6, num.rolls, replace = T))
}
```
Note for help with functions in R, type `?sample`.

## Exercise: Writing and Documenting a Function
Use the defined style guidelines to create an R script that:

1. Takes a state abbreviations as an input
2. Imports a file available at:  [http://math.montana.edu/ahoegh/teaching/stat408/datasets/HousingSales.csv](http://math.montana.edu/ahoegh/teaching/stat408/datasets/HousingSales.csv)
3. Creates a subset of housing sales from that state.
4. Returns a vector with the mean closing price in that state.

Verify your functions works by running it twice using "MT" and "NE" as inputs.

## Exercise: Functions Part 2
Now write a function that;

1. Takes daily snowfall total in inches as input
2. Takes day of week as input
3. Returns whether to ski or stay home.

Also include and the `stop()` function for errors.
Test this function with two settings:

 - snowfall = 15, day = "Sat"
 - snowfall = -1, day = "Mon"

## Exercise: Aggregate
Earlier we wrote a function to compute the average housing price for two states, now use aggregate to compute this for all the states in the housing data set.
