100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Functions in R

How R functions are defined, scoped, and evaluated — covering default arguments, lexical scoping, return values, and the ... variadic argument.

Control Flow & FunctionsIntermediate9 min readJul 10, 2026
Analogies

Introduction to Functions in R

Functions in R are first-class objects created with the function() keyword, bundling a block of reusable code together with named parameters, and — like everything else in R — a function itself can be stored in a variable, passed as an argument to another function, or returned from one. This first-class treatment is what makes higher-order patterns like sapply(x, FUN) possible, where FUN is simply another value being passed around.

🏏

Cricket analogy: A well-drilled fielding routine — like the specific relay throw from deep cover to the keeper — can be handed to any fielder on the team and executed identically, the way a function packages logic that can be called from anywhere in a script.

Defining Functions and Default Arguments

A function is defined as function(arg1, arg2 = default_value) { body }, where parameters can be given default values that are used whenever the caller omits that argument; arguments can also be matched by position or by explicit name, and named matching can be mixed with positional matching as long as named arguments are unambiguous. Because default values are just ordinary R expressions, a default can even reference another parameter of the same function, such as function(x, n = length(x)).

🏏

Cricket analogy: A net session booking form has fields like bowler_type = 'pace' as a default, so if a batsman doesn't specify, they automatically face pace bowling unless they explicitly request spin — like a default argument.

r
bmi <- function(weight_kg, height_m = 1.75) {
  weight_kg / (height_m^2)
}

bmi(70)          # uses default height_m = 1.75
bmi(70, 1.80)    # overrides the default
bmi(weight_kg = 70, height_m = 1.68)  # named arguments

Scoping and the Return Value

R uses lexical scoping, meaning a function looks up free variables in the environment where it was defined, not in the environment of whoever calls it, so a function's behavior doesn't change based on what variables happen to exist at the call site. A function's return value is the value of the last evaluated expression in its body, or whatever is passed to an explicit return() call, and the superassignment operator <<- lets a function modify a variable in an enclosing (typically the global) environment rather than creating a new local one.

🏏

Cricket analogy: A bowler's action is grooved in the nets where they trained, not adapted to whichever ground they later play at, just as a function's variable lookups are fixed to where it was defined, not where it's called from.

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

counter <- make_counter()
counter()  # 1
counter()  # 2
counter()  # 3

Variadic Arguments with ...

The special ... argument lets a function accept an arbitrary number of additional arguments, which can then be forwarded wholesale to another function inside the body, a pattern used heavily in R's plotting and modeling functions so that, for example, a custom wrapper around plot() can pass along col, pch, or any other graphical parameter the caller supplies without the wrapper needing to name each one explicitly. Inside the function, list(...) captures those extra arguments as a named list, and ..1, ..2, and so on can access them positionally.

🏏

Cricket analogy: A tour operator's package(destination, ...) forwards whatever extras a client requests — visa help, kit hire, insurance — straight to the relevant specialist supplier without the operator needing to know every possible extra in advance, just like ... forwarding arguments.

Because functions are first-class objects, you can write higher-order functions like function(f, x) f(x) that accept another function as an argument — this is exactly how sapply(), lapply(), and Map() are able to apply an arbitrary function you supply to each element of a vector or list.

R uses lazy evaluation for arguments — a default value like n = length(x) is not computed until n is actually used inside the function body, which means if x is modified before n is first referenced, the default reflects the modified x, not the value at call time; use force(n) early in the function if you need to pin the value immediately.

  • Functions are first-class objects in R and can be assigned to variables, passed as arguments, and returned from other functions.
  • Default argument values are ordinary expressions and can reference other parameters, e.g. n = length(x).
  • R uses lexical scoping: a function resolves free variables based on where it was defined, not where it's called.
  • The return value is the last evaluated expression, or the argument to an explicit return() call.
  • <<- assigns into an enclosing environment instead of creating a new local variable.
  • ... captures an arbitrary number of extra arguments and can forward them to another function.
  • Arguments are lazily evaluated as promises, only computed the first time they're actually used.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#RProgrammingStudyNotes#FunctionsInR#Functions#Defining#Default#Arguments#StudyNotes#SkillVeris#ExamPrep