In this lesson, you will learn to:
Write your own functions in R
Make good decisions about function arguments and returns
Include side effects and/or error messages in your functions
Use good R code style
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.
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?
add_or_subtract
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…
first_num
second_num
result
result_2