Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 39 ยท Control Flow and Functions

Writing Functions in R

Write your own R functions. Learn function(), default and named arguments, return values, validating input with stop(), scope, closures, anonymous functions and the pipe.

You have been calling functions since the first lesson: sum(), mean(), paste(). Now you will write your own. A function packages a piece of logic under a name so you can reuse it, test it once and stop repeating yourself. The rule of thumb among R programmers: if you copy and paste a chunk of code more than twice, turn it into a function.

In R, functions are ordinary values. You create one with the function keyword and assign it to a name, exactly like a number or a vector.

Defining and calling a function

R
area <- function(width, height) {
  width * height
}

area(3, 4)
#> [1] 12

The parts are:

  • Arguments (width, height): the inputs, listed in parentheses.
  • Body: the code between the braces.
  • Return value: the last expression evaluated is returned automatically.

Because the body has just one expression, braces are optional: circle_area <- function(r) pi * r^2 works, and circle_area(2) gives [1] 12.56637.

You can write return() explicitly. Most R style guides use it only for early exits:

R
safe_divide <- function(a, b) {
  if (b == 0) {
    return(NA)          # leave early
  }
  a / b
}

safe_divide(10, 4)
#> [1] 2.5

safe_divide(1, 0)
#> [1] NA

Default and named arguments

Give an argument a default with =. Callers may then leave it out:

R
price_with_tax <- function(price, rate = 0.2) {
  price * (1 + rate)
}

price_with_tax(100)
#> [1] 120

price_with_tax(100, rate = 0.1)
#> [1] 110

You may pass arguments by position or by name. Names make calls readable and let you reorder them: price_with_tax(rate = 0.1, price = 100). Use names for anything beyond the first one or two obvious arguments.

The dots argument

... collects any extra arguments and can pass them on to another function:

R
total <- function(...) {
  sum(...)
}

total(1, 2, 3)
#> [1] 6

shout <- function(text, ...) {
  paste(toupper(text), ...)
}

This is how functions like paste() and c() accept any number of values. You can see the contents with list(...).

Returning several values

A function returns one object. To return more, return a list (see Lists):

R
describe <- function(x) {
  list(mean = mean(x), sd = sd(x))
}

result <- describe(c(2, 4, 4, 4, 5, 5, 7, 9))
result$mean
#> [1] 5

result$sd
#> [1] 2.13809

Checking inputs

Fail early with clear messages. stop() raises an error, warning() raises a warning, stopifnot() checks assumptions:

R
mean_of <- function(x) {
  if (!is.numeric(x)) {
    stop("x must be numeric")
  }
  sum(x) / length(x)
}

mean_of("a")
#> Error in mean_of("a") : x must be numeric
R
average_age <- function(ages) {
  stopifnot(is.numeric(ages), length(ages) > 0)
  mean(ages)
}

You will learn to handle errors, not only raise them, in Errors and Debugging.

Scope: where variables live

Variables created inside a function are local. They exist only while it runs and do not touch the outside:

R
x <- 10

f <- function() {
  x <- 5      # a new, local x
  x
}

f()
#> [1] 5

x
#> [1] 10

If a name is not found inside the function, R looks outward, in the environment where the function was defined. So a function can read a global variable, but ordinary assignment never changes it. Passing what a function needs as arguments, rather than relying on globals, makes it predictable.

Closures

A function that is created inside another function remembers the surroundings it was created in. That lets you build functions with private state:

R
make_counter <- function() {
  count <- 0
  function() {
    count <<- count + 1
    count
  }
}

counter <- make_counter()
counter()
#> [1] 1
counter()
#> [1] 2
counter()
#> [1] 3

The superassignment arrow <<- changes count in the enclosing environment. Use it sparingly.

Functions are values

Since functions are objects, you can pass them to other functions. This is the idea behind the apply family:

R
apply_twice <- function(f, x) f(f(x))

apply_twice(sqrt, 16)
#> [1] 2

For short one-off functions, R 4.1 added a compact anonymous function syntax with a backslash:

R
sapply(1:3, \(i) i * 10)
#> [1] 10 20 30

\(i) i * 10 means function(i) i * 10.

The pipe

The native pipe |> passes the result on the left as the first argument of the function on the right. It lets you read code in the order it happens:

R
c(4, 9, 16) |> sqrt() |> sum()
#> [1] 9

That equals sum(sqrt(c(4, 9, 16))) (2 + 3 + 4 = 9), but reads from left to right. The tidyverse uses pipes heavily, as you will see in dplyr Basics. (The older %>% from the magrittr package does a similar job.)

Anatomy of a function

Name area <- function
Arguments Inputs, with defaults
Body The steps in braces
Result Last value returned

Local variables vanish when the function ends.

1 / 2

Documenting your function

Add a comment above the function saying what it does, what the arguments mean, and what it returns. Several packages (for example roxygen2) turn such comments into official help pages. Even a two-line comment helps your future self.

Common mistakes

  1. Forgetting that the last value is returned. A final assignment such as y <- x * 2 returns y invisibly, so nothing prints.
  2. Relying on global variables that may change.
  3. Using = instead of == inside the function.
  4. Modifying an argument and expecting the caller's variable to change. R passes copies, so the original stays the same unless you return and reassign.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a function return if it has no explicit return()?

    R returns the last evaluated expression. return() is mainly for early exits.
  2. 2. Given x <- 10 and f <- function() { x <- 5; x }, what is x after calling f()?

    The assignment inside f creates a local x. The global x is unchanged.
  3. 3. How do you give an argument a default value?

    Use = in the argument list.
  4. 4. What does c(1, 4, 9) |> sqrt() |> sum() return?

    sqrt gives 1, 2, 3 and sum gives 6.
  5. 5. How can a function return two separate results?

    A function returns one object, so bundle several values into a list.

Summary

  • Create functions with name <- function(args) { body }; the last expression is the result.
  • Use defaults, named arguments and ... for flexible calls.
  • Return several values in a list; validate inputs with stop() and stopifnot().
  • Variables inside a function are local; closures remember their creation environment.
  • Functions are values: pass them around, write short ones as \(x) ..., and chain steps with |>.

Next: The apply Family