ZetCode

R functions

last modified November 19, 2026

A function is a block of code with a name that can be called whenever the work is needed. Functions remove duplication, give a calculation a meaningful name, and make the rest of a script easier to read. In R a function is an ordinary object: it is created with the function keyword, assigned to a name like any other value, and can be passed to other functions. This article covers definitions, parameters, defaults, return values, variable arguments, and the evaluation rules that make R functions distinctive.

Defining and calling a function

A definition has three parts: the keyword function, a parenthesised list of parameters, and a body in braces. The parameters are the names the body uses for its inputs; the values supplied in a call are called arguments. Assignment gives the function a name, and a later call runs the body with the arguments bound to the parameters.

greet.R
greet <- function(name) {
  cat("Hello,", name, "\n")
}
greet("Ada")
greet("Grace")

The function has one parameter, name, and the two calls supply two different arguments. The body runs in a new environment that contains name, so each call works with its own value and the calls do not interfere. The function is defined once and can be called any number of times, which is the main reason to write one.

$ Rscript greet.R
Hello, Ada 
Hello, Grace 

Parameters and defaults

A parameter can have a default value, written after an equals sign in the definition. A caller that does not supply the parameter gets the default, and a caller that does supply it overrides the default. Defaults make a function convenient for the common case while keeping the less common case available.

power-defaults.R
power <- function(x, exponent = 2) {
  x ^ exponent
}
cat("square:", power(5), "\n")
cat("cube:", power(5, 3), "\n")
cat("named:", power(exponent = 3, x = 2), "\n")

The first call uses the default exponent and squares five. The second passes three and cubes five. The third uses named arguments, which bind by name rather than by position, so the order of the call does not have to match the order of the definition. Named arguments are also the reason the equals sign appears inside function calls: it is not assignment there.

$ Rscript power-defaults.R
square: 25 
cube: 125 
named: 8 

Return values

A function returns the value of the last expression in its body. The return function makes the exit explicit and stops the body immediately, which is useful when a later part of the body should not run. Every function returns something; a function whose last expression is cat returns the result of cat, which is NULL.

returns.R
sign_of <- function(x) {
  if (x > 0) {
    return("positive")
  }
  if (x < 0) {
    return("negative")
  }
  "zero"
}
cat(sign_of(5), "\n")
cat(sign_of(-5), "\n")
cat(sign_of(0), "\n")

The first two calls leave through return, and the last falls through to the final string, which is then the return value. A function can return any object: a number, a string, a vector, a list, or another function. The value is usually assigned or printed by the caller, as the three cat calls do here.

$ Rscript returns.R
positive 
negative 
zero 

Variable arguments

The special parameter written as three dots, ..., accepts any number of extra arguments, named or not. Inside the body they can be collected into a vector with c(...) or passed on to another function that also accepts dots. This is how functions such as sum and cat take a flexible number of values.

dots.R
describe <- function(...) {
  values <- c(...)
  cat("count:", length(values), "\n")
  cat("mean:", mean(values), "\n")
}
describe(2, 4, 6, 8)

The call supplies four arguments, and c(...) turns them into one vector. length returns the number of elements and mean computes their average. A function with dots should document which arguments it forwards, because a misspelled name inside ... is not caught by the argument matching of the function itself.

$ Rscript dots.R
count: 4 
mean: 5 

Lazy evaluation

R evaluates arguments only when the body first uses them, a rule called lazy evaluation. An argument that is never used is never evaluated, even when its expression would print something or take a long time. This allows a function to ignore an argument deliberately and to pass expressions through without running them.

lazy.R
ignore <- function(x) {
  "done"
}
print(ignore(print("evaluated")))

The word evaluated does not appear, because the body never reads x. The call inside the argument list is a promise: an expression plus the environment where it would be evaluated. The promise is forced only when the parameter is used, and the result is then cached for the rest of the call. Lazy evaluation is convenient, but it also means that an error in an unused argument stays hidden until the argument is used.

$ Rscript lazy.R
[1] "done"

Missing arguments

The function missing tests whether a parameter received a value. It is useful when a default cannot be written in the parameter list because the replacement depends on the other arguments. The test must run before the parameter is used, since using a missing parameter produces an error.

missing-args.R
greet <- function(name) {
  if (missing(name)) {
    name <- "there"
  }
  cat("Hello,", name, "\n")
}
greet()
greet("Ada")

The first call supplies nothing, so missing(name) is true and the body assigns the fallback. The second call supplies a name, so the test is false and the assignment is skipped. Writing name = "there" in the parameter list would be shorter for a fixed default; missing is for cases where the fallback is computed from other arguments or where the difference between an absent and an empty value matters.

$ Rscript missing-args.R
Hello, there 
Hello, Ada 

Invisible return values

A function can return a value without having it printed automatically by wrapping the result in invisible. The console still receives the value, and an assignment can store it, but a bare call prints nothing. Functions that are called for their side effect, such as library or an assignment, use this convention.

invisible-result.R
twice <- function(x) {
  invisible(x * 2)
}
twice(5)
print(twice(5))

The bare call produces no output, while print forces the value to be shown. The value is not lost: an assignment such as result <- twice(5) stores ten. Invisibility affects only the automatic printing at the top level, not the value itself.

$ Rscript invisible-result.R
[1] 10

Scope and lexical rules

A function looks up names that are not parameters in its enclosing environment, the environment where the function was defined. This rule is called lexical scoping. A name assigned inside the body creates a local object, and a name that is only read is searched outward through the enclosing environments up to the global environment.

scope.R
x <- 10
show_x <- function() {
  cat("inside show_x:", x, "\n")
}
change_x <- function() {
  x <- 20
  cat("inside change_x:", x, "\n")
}
show_x()
change_x()
cat("outside:", x, "\n")

show_x finds the global x because it does not define its own. change_x assigns a local x, which hides the global one for the rest of its body, so the global value stays ten. Changing the outer value from inside a function requires the superassignment operator <<-, described in the variables article.

$ Rscript scope.R
inside show_x: 10 
inside change_x: 20 
outside: 10 

A complete example

The next script defines a function for compound interest and calls it with three rates. The function takes the principal, the annual rate, and the number of years, and returns the final amount. The loop comes from the control flow article, and the calculation uses the same formula as the operators article.

interest.R
amount <- function(principal, rate, years) {
  principal * (1 + rate) ^ years
}
for (rate in c(0.03, 0.05, 0.07)) {
  cat(rate, "->", round(amount(1000, rate, 10), 2), "\n")
}

The function is written once and reused three times with a different rate each time. The loop supplies the varying argument, and the function supplies the formula. A result of 1343.92 corresponds to three percent, 1628.89 to five percent, and 1967.15 to seven percent, all over ten years. Separating the formula from the repetition is what makes the script short and easy to change.

$ Rscript interest.R
0.03 -> 1343.92 
0.05 -> 1628.89 
0.07 -> 1967.15 

Next steps

The vectorisation article later in the series shows how vectorised functions replace many loops, and the apply-family article shows how to call a function for every element of a list or every column of a data frame. The closures article returns to functions that create other functions and keep state between calls.

Source

The R Language Definition: functions

An Introduction to R: writing your own functions

R documentation: function definitions

R documentation: invisible

In this article we have defined functions with the function keyword, given parameters default values, and called them with positional and named arguments. We returned values explicitly and implicitly, collected variable arguments with ..., and saw how lazy evaluation delays an argument until it is used. We tested missing arguments, returned invisible values, and followed the lexical rule that decides where a free name is found. The series continues with vectorisation.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.