Function (R)

A function in R is a reusable block of code created with the function keyword and assigned to a name. Functions are first-class objects: you can pass them as arguments and return them from other functions.

R

You define a function with name <- function(args) { body }. The value of the last evaluated expression is returned automatically, though you can use return() to exit early. Arguments can have default values (function(x, n = 2)), and the special ... parameter collects extra arguments to pass along.

Functions are first-class values in R — you can store them in lists, pass them to apply/lapply, and return them from other functions, which is why R is well suited to functional programming. Anonymous functions (function(x) x^2, or the shorthand \(x) x^2 in R 4.1+) are common as arguments.

R uses lexical scoping: a function looks up variables in the environment where it was defined. This enables closures — functions that remember values from their creating scope — a powerful pattern for building configurable behavior.

Syntax

square <- function(x) {
  x * x
}
square(5)

Examples

R

greet <- function(name, greeting = "Hello") {
  paste0(greeting, ", ", name, "!")
}
print(greet("Ana"))
print(greet("Sam", greeting = "Hi"))

Output:

[1] "Hello, Ana!"
[1] "Hi, Sam!"

Learn it in a lesson

See also

Back to the Dictionary