Note: Your exam will be in a similar format to this (RMarkdown File with Questions and Code chunks for your answers), so make sure you have the process for knitting to html working.

In Class Activity

The questions from your notes today are below, please copy your answers them here! Then complete the two new tasks, and attempt the “hard mode” if you have time.

  1. Write your own function that takes the temperature in Fahrenheit as an argument and returns the Celcius equivalent.
calculate_celcius <- function(fahrenheit) {
  celcius <- (5/9 * (fahrenheit-32))
  celcius
}
calculate_celcius(50)
## [1] 10
  1. Expand that function so that it takes a temperature in Fahrenheit and a distance in feet and returns both the temperature in Celcius and the distance in meters (you’ll likely need to remember the c() function!)
convert_fn <- function(fahrenheit, feet){
  celcius <- (5/9 * (fahrenheit-32))
  meter <- (0.3048 * feet)
  result <- c(celcius,meter)
  return(result)
}

convert_fn(40,120)
## [1]  4.444444 36.576000
  1. Write a function that prints out a statement of whether the number passed as an argument is positive, negative or 0.
check_number <- function(input){
  if(input > 0){
    statement <- c("The input is positive")
  }
  else if (input <0) {
    statement <- c("The input is negative")
  }
  else {
    statement <- c("The input is zero")
  }
  return(statement)
  
}

check_number(20)
## [1] "The input is positive"
check_number(-10)
## [1] "The input is negative"
check_number(0)
## [1] "The input is zero"
  1. Write a function that returns the absolute value of the number passed as an argument.
    • Don’t use abs(). Use the flow from problem 1 and multiply by negative one as necessary.
my_abs <- function(input){
  if(input > 0){
    result = input
  }
  else if (input <0) {
    result = input * (-1)
  }
  else {
    result = 0
  }
  return(result)
  
}

my_abs(-20)
## [1] 20
my_abs(10)
## [1] 10
my_abs(0)
## [1] 0
  1. Hard mode: add an error check to that function that prints out the string “Please pass a numerical value to this function” if the user passes the function a string.
    • There are functions that check and return T/F: is.numeric() or is.character() would be relevant here
my_abs_errorCheck <- function(input){
  if(is.numeric(input)){
    if(input > 0){
      result = input
    }
    else if (input <0) {
      result = input * (-1)
    }
    else {
      result = 0
    }
    return(result)
  }
  else if (is.character(input)){
    result <- c("Please pass a numerical value to this function")
    return(result)
  }
}

my_abs_errorCheck(-20)
## [1] 20
my_abs_errorCheck(10)
## [1] 10
my_abs_errorCheck(0)
## [1] 0
my_abs_errorCheck("Hello Dr Shoemaker")
## [1] "Please pass a numerical value to this function"

```