Function definition

Author

Marie-Hélène Burle

R comes with a number of built-in functions. Packages can provide additional ones. In many cases however, you will want to create your own functions to perform exactly the computations that you need.

In this section, we will see how to define new functions.

Syntax

Here is the syntax to define a new function:

name <- function(arguments) {
  body
}

Example

Let’s define a function that we call compare which will compare the value between 2 numbers:

compare <- function(x, y) {
  x == y
}
  • compare is the name of our function.
  • x and y are the placeholders for the arguments that our function will accept (our function will need 2 arguments to run successfully).
  • x == y is the body of the function, that is, the computation performed by our function.

We can now use our function:

compare(2, 3)
[1] FALSE

What is returned by a function?

In R, the result of the last statement is printed automatically:

test <- function(x, y) {
  x
  y
}
test(2, 3)
[1] 3

If you want to also print other results, you need to explicitly use the print() function:

test <- function(x, y) {
  print(x)
  y
}
test(2, 3)
[1] 2
[1] 3

Note that, unlike print(), the function return() exits the function:

test <- function(x, y) {
  return(x)
  y
}
test(2, 3)
[1] 2
test <- function(x, y) {
  return(x)
  return(y)
}
test(2, 3)
[1] 2