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
Write a function called find_car_make()
that takes as input the name of a car, and returns only the “make”, or the company that created the car. For example, find_car_make("Toyota Camry")
should return "Toyota"
and find_car_make("Ford Anglica")
should return "Ford"
. (You can assume that the first word of a car name is always its make.)
Use your function with the built-in dataset mtcars
, to create a new column in the data called make
that gives the company of the car.
Hint: You should start by using the function dplyr::rownames_to_column()
, so that the car names are a variable in the data frame instead of row labels.
Consider the following two chunks of code:
avg_by_species <-
penguins %>%
group_by(species) %>%
summarize(
avg_mass = mean(body_mass_g, na.rm = TRUE)
)
Which one is easier to read? The second one, of course!
Part of writing reproducible and shareable code is following good style guidelines. Mostly, this means choosing good object names and using white space in a consistent and clear way.
There is no need to read this full resource, but please skim through it and read some of the examples.
Designing functions is somewhat subjective, but there are a few principles that apply:
library()
statements inside functions!)Identify five major violations of design principles for the following function: