## Exercise: Order of operations

Note that order of operations is important in writing R code.

4 - 2 ^ 2
5 * 2 - 3 ^ 2
! TRUE & pi == 3 # & and operator
! (TRUE | FALSE) # | or operator

Write out the mathematical representation for the first two expressions and then evaluate all four expressions. Note ! is R’s not operator.

## Solution: Order of operations

The results of the R code are:

## Exercise: Function Descriptions

• Document this function with
1. a description,
2. summary of input(s)
3. summary of outputs
RollDice <- function(num.rolls){
#
# ARGS:
# RETURNS:
return(sample(6, num.rolls, replace = T))
}
RollDice(2)
## [1] 4 5

## Solution: Function Descriptions

RollDice <- function(num.rolls){
#
# ARGS:
# RETURNS:
return(sample(6, num.rolls, replace = T))
}
RollDice(2)
## [1] 4 6

## Exercise: Writing and Documenting a Function

Use the defined style guidelines to create an R script that:

1. Takes two state abbreviations as inputs
2. Imports a file available at: http://math.montana.edu/ahoegh/teaching/stat408/datasets/HousingSales.csv
3. Creates two subsets of housing sales in the two states.
4. Returns a vector with the mean closing price in the two states.

Verify your functions works by using “MT” and “NE” as inputs.

## Solution: Writing and Documenting a Function

SummarizeHousingCosts <- function(state1, state2){

}
SummarizeHousingCosts('MT','NE')
## NULL

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

## Solution: Functions Part 2

ToSki <- function(snowfall, day){

}
ToSki(snowfall = 15, day = "Sat")
## NULL
ToSki(-1, 'Mon')
## NULL

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

## Solution: 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.

housing.prices <- read.csv(
'http://math.montana.edu/ahoegh/teaching/stat408/datasets/HousingSales.csv',
stringsAsFactors = F)
#housing.prices.state <- aggregate(

# head(housing.prices.state)