Learn R Programming  /  Functions  /  Functions

Functions

A function is a reusable block of code that takes inputs, does something with them, and gives back a result. Functions are how you avoid repeating yourself in R.

Defining a Function

R Code
square <- function(x) {
  return(x^2)
}

square(5)
Output
[1] 25
💡 Tip
R automatically returns the value of the LAST expression evaluated in a function, so return() is often optional. square <- function(x) x^2 works exactly the same way as the example above.

Multiple Arguments and Defaults

R Code
greet <- function(name, greeting = "Hello") {
  paste(greeting, ",", name, "!")
}

greet("Rafi")
greet("Meera", greeting = "Hi")
Output
[1] "Hello , Rafi !"
[1] "Hi , Meera !"

Argument Matching: Position vs Name

R Code
bmi <- function(weight, height) {
  round(weight / height^2, 1)
}

bmi(70, 1.75)               # matched by position
bmi(height = 1.75, weight = 70)  # matched by name, order does not matter
Output
[1] 22.9
[1] 22.9

The ... (Dots) Argument

... lets a function accept any number of extra arguments and pass them along to another function inside.

R Code
summarise_all <- function(...) {
  values <- c(...)
  cat("Mean:", mean(values), " Max:", max(values), "\n")
}

summarise_all(4, 8, 15, 16, 23)
Output
Mean: 13.2  Max: 23

Scope: Local vs Global Variables

A variable created inside a function only exists inside that function - it does not affect anything outside.

R Code
x <- 10   # global x

modify <- function() {
  x <- 99   # this x is LOCAL to the function
  print(x)
}

modify()
print(x)  # unchanged outside the function
Output
[1] 99
[1] 10
⚠ Common Mistake
Beginners sometimes expect a variable changed inside a function to also change outside it. In R, functions do not modify variables in the surrounding environment unless you explicitly use the <<- operator, which is rarely needed and best avoided while learning.

Advanced: Recursive Functions

🚀 Advanced Example
A recursive function calls itself. Here, factorial(n) is defined in terms of factorial(n-1), stopping at a base case.
R Code
factorial_r <- function(n) {
  if (n <= 1) {
    return(1)
  }
  return(n * factorial_r(n - 1))
}

factorial_r(5)   # 5 * 4 * 3 * 2 * 1
Output
[1] 120

Key Points

  • Define a function with function(args) { body }; the last evaluated line is returned automatically.
  • Give arguments default values with name = default_value.
  • ... lets a function forward an unknown number of extra arguments.
  • Variables created inside a function stay local and do not leak into the surrounding code.