Writing R Functions


In this lesson, you will learn to:


Time Estimates:
     Videos: 30 min
     Readings: 10-30 min
     Activities: 60-90 min
     Check-ins: 4



Writing Functions



Required Video: Writing Functions




Required Tutorial: Primer: Writing Functions



Recommended Reading: R4DS: Functions




Check-In 1: Simple Functions


Write a function called times_seven() which takes a single argument and multiplies by 7.

This function should check that the argument is numeric.

This function should also excitedly announce (print) “I love sevens!” if the argument to the function is a 7.



Check-In 2: Predicting Function Behavior


add_or_subtract <- function(first_num, second_num = 2, type = "add") {
  
  if (type == "add") {
    first_num + second_num
  } else if (type == "subtract") {
    first_num - second_num
  } else {
    stop("Please choose `add` or `subtract` as the type.")
  }
  
}

Question 1: What will be returned by each of the following?

  1. 1
  2. -1
  3. 30
  4. An error defined in the function add_or_subtract
  5. An error defined in a different function, that is called from inside add_or_subtract
add_or_subtract(5, 6, type = "subtract")

add_or_subtract("orange")

add_or_subtract(5, 6, type = "multiply")

add_or_subtract("orange", type = "multiply")

Question 2:

Consider the following code:

first_num <- 5
second_num <- 3

result <- 8

result <- add_or_subtract(first_num, second_num = 4)

result_2 <- add_or_subtract(first_num)

In your Global Environment, what is the value of…

  1. first_num
  2. second_num
  3. result
  4. result_2