45 function

Written by Haoluan Chen and last updated on 7 October 2021.

45.1 Introduction

In this lesson, you will learn how to:

  • Write your own functions in R

Prerequisite skills include:

  • setup RStudio
  • run R code in the console

Highlights:

  • Write your own function

45.2 The content

Function in R is a set of statements organized together to perform a specific task.

The function consists of four parts:

  • Function Name: This is the name of the function. It is stored in the R environment as an object.

  • Arguments/Parameters: Just like in math, a function has an input and an output. Arguments/Parameters are the inputs of the function. However, parameters can be required or have default values. Parameters are specified inside a () and split by comma.

  • Function Body: The function body contains a set of statements that defines what the function does. The function body is inside a {}.

  • Return Value: The return value of a function is the last expression in the function body to be evaluated. This is the output of the function.

45.2.1 Why and when should you use it?

Instead of copy and pasting your code multiple times, functions allow you to perform repetitive tasks automatically. It has three advantages over using copy and paste:

  • You can give a function an informative name that makes your code easier to understand.

  • As requirements change, you only need to update code in one place instead of many.

  • You eliminate the chance of making incidental mistakes

You should consider writing a function whenever you have copied and pasted a block of code more than twice.

45.2.2 Built-in functions

There are many built-in functions in R. For example, the mean() function in R can calculate the mean of a vector. Whenever we want to calculate a mean of some numbers, we do not have to calculate the sum of all the numbers and divide by the number of numbers. Instead, we can store the numbers in a vector then call the mean() function to calculate the mean. Utilize the built-in functions can make your life easier for your projects.

45.2.3 User defined functions

We can also write our own function for some specific task.

Here is a very simple function call the sum_of_two_numbers.

sum_of_two_numbers <- function(a, b){
  y = a + b
  y
}

In this function, it consists of four parts:

  • sum_of_two_numbers is the name of the function
  • a and b is the input of this function
  • y = a + b and y inside the {} is the body of the function
  • y is the output of this function because it is the last expression in the function body to be evaluated.

We can use this function by calling the function name and specifying the input value in the bracket. We can use the following code to calculate the sum of 2 and 3.

sum_of_two_numbers(2,3)
#> [1] 5

45.2.4 default parameters

The parameters can have a default value. For example, we can set the parameter b to 3 in our sum_of_two_numbers function.

sum_of_two_numbers <- function(a, b = 3){
  y = a + b
  y
}

Now, if we do not specify parameter b in our function call, then b is set to 3 in default.

sum_of_two_numbers(2)
#> [1] 5

Here, we tell R to run the body of sum_of_two_numbers with a = 2, and b is set to the default number 3.

However, we can still specify parameter b in our function call to calculate the sum of two numbers.

sum_of_two_numbers(2, 5)
#> [1] 7

Here, we tell R to run the body of sum_of_two_numbers with a = 2 and b = 5.

45.3 Exercises

45.3.0.1 Exercise 1

Change the name of the sum_of_two_numbers to mean_of_two_number and modify the function body to calculate the mean of two numbers.

sum_of_two_numbers <- function(a, b){
  y = a + b
  y
}
mean_of_two_numbers <- function(a, b){
  y = (a + b)/2
  y
}

45.3.0.2 Exercise 2

Write a function called product that takes two numbers as input and calculate the product of two numbers.

product <- function(a, b){
  y = a * b
  y
}

45.3.0.3 Exercise 3

Here is the mean_of_two_numbers function in Exercise 1. Set the parameter a to a default value of 6.

mean_of_two_numbers <- function(a, b){
  y = (a + b)/2
  y
}
mean_of_two_numbers <- function(a = 6, b){
  y = (a + b)/2
  y
}

45.3.0.4 Exercise 4

Predict the output of the following code.

mean_of_two_numbers <- function(a = 6, b){
  y = (a + b)/2
  y
}
mean_of_two_numbers(3, 5)
#> [1] 4
4
#> [1] 4

45.4 Common mistakes & errors

  • Make sure you have correct input for your function
  • Remember that the function returns the last expression in the function body.
  • Make sure you define your argument in () and your function body in {}.
  • Make sure you define your function before calling it.

45.5 Next steps

Most of the time, you will be using the function from various packages and the functions in R. However, for some specific tasks, you will have to write your own functions. The ability to use user-defined functions and functions from different packages makes R a powerful tool in Data Science.

If you want to see more completed function, you can read through this Function chapter in R for Data Science https://r4ds.had.co.nz/functions.html#when-should-you-write-a-function

45.6 Exercises

45.6.1 Question 1

Function in R is a set of statements organized together to perform a specific task. a. True b. False

45.6.2 Question 2

Function contains: a. Function Name b. Arguments/Parameters c. Function Body d. Return Value e. All of the above

45.6.3 Question 3

You should consider writing a function whenever you have copied and pasted a block of code more than twice. a. True b. False

45.6.4 Question 4

mean() is not a built-in function in R a. True b. False

45.6.5 Question 5

You should avoid use built in functions in R a. True b. False

45.6.6 Question 6

How many parameters can you have in a function? a. 1 b. 2 c. 10 d. As much as you need

45.6.7 Question 7

Can we use built-in function inside our function? a. Yes b. No

45.6.8 Question 8

The function parameters can have a default value. a. True b. False

45.6.9 Question 9

Function returns the last expression in the function body. a. True b. False

45.6.10 Question 10

Function is an object in R environment.
a. True b. False