R Functions

A function bundles a piece of reusable R code under a name, so you can run the same logic again and again just by calling that name instead of retyping the code.

Why write your own functions

As scripts grow, you'll often find yourself repeating very similar chunks of code with just a few values changed. Wrapping that logic in a function lets you write it once, give it a clear name, and reuse it anywhere, which cuts down on copy-paste mistakes and makes your script easier to read at a glance.

Example

greet <- function(name) {
  paste("Hello,", name)
}

greet("Asha")
greet("Ravi")

The parts of a function

  • Name: the identifier you use to call the function later, such as greet
  • function(...) keyword: marks the start of a function definition and lists its parameters
  • Body: the block of code in curly braces that runs each time the function is called
  • Return value: the result the function produces, which you can store, print, or use in further calculations

R doesn't always require the word return. If the last line of a function's body is an expression, R automatically returns its value. Writing return(value) explicitly is still useful when you want to exit a function early, before reaching its last line.

Implicit vs. Explicit Return

classify <- function(score) {
  if (score < 0) {
    return("invalid")  # exits early
  }
  if (score >= 60) "pass" else "fail"  # last expression is returned automatically
}

classify(75)
classify(-5)

Reusing a function across many inputs

Reuse Example

circle_area <- function(radius) {
  pi * radius^2
}

circle_area(1)
circle_area(2.5)
circle_area(10)
Note: Functions in R are ordinary objects. You can store one in a variable, pass it to another function as an argument, or type its name without parentheses to see its definition printed out.

Variable scope inside a function

Variables created inside a function's body are local to that function, they exist only while the function is running and disappear once it finishes. This means a variable named total inside one function won't clash with a different total defined outside it or in another function, which keeps functions self-contained and easier to reason about.

Exercise: R Functions

If an R function body has no explicit return() call, what does the function return?