01 / 20
f(x)

Defining Functions
in R Programming

Learn how to create reusable blocks of code using function(), pass arguments, and return values to write cleaner, more powerful R programs.

R Programming

What Is a Function?

A function is a named, reusable block of code that takes inputs (arguments), performs a task, and returns an output. Think of it like a machine: you feed something in, something comes out.

Input(s) function() Process Output

Why Define Your Own Functions?

Reusability
Write code once, call it as many times as you need: no copy-pasting.
Readability
Give complex operations a meaningful name so your script reads like English.
Debugging
Fix a bug in one place and every call to that function is fixed automatically.

Anatomy of an R Function

my_function <- function ( arg1 , arg2 ) { # body: do something result <- arg1 + arg2 return ( result ) } NAME ARGUMENTS BODY RETURN VALUE Name + function keyword Arguments (inputs) Body (logic) return() sends output back

The function() Keyword

In R, function() is a special keyword that creates a new function object. You assign it to a name using the assignment operator <-.

# General syntax name <- function(parameters) { # code to execute return(value) }

Arguments vs Parameters

Parameter
The placeholder name in the function definition. Like a variable waiting for a value.
Argument
The actual value you pass when calling the function. It fills in the parameter.
# 'x' is the parameter square <- function(x) { return(x * x) } # 5 is the argument square(5) # returns 25

How Return Values Work

R functions can return values in two ways. Understanding both is essential for writing predictable code.

1
Explicit return: Use return(value) to immediately exit the function and send back the value.
2
Implicit return: If no return() is called, R automatically returns the last evaluated expression in the function body.
# Explicit add <- function(a, b) { return(a + b) } # Implicit (same result) add <- function(a, b) { a + b }

Explicit vs Implicit Return

Explicit return() Implicit (last expression)
Syntax return(value) Just write the expression
Clarity Very clear intent Shorter, R-idiomatic
Early exit? Yes: can exit mid-body No: always runs to end
Best for Complex, multi-branch logic Short, simple functions

Setting Default Arguments

You can give parameters default values so the caller doesn't have to supply every argument. If they do pass a value, it overrides the default.

greet <- function(name, greeting = "Hello") { paste(greeting, name) } greet("Alice") # "Hello Alice" greet("Bob", "Hi") # "Hi Bob"

How to Write a Function

1
Choose a name that describes the action: calculate_area, not func1.
2
Identify inputs: What values does your logic need? List them as parameters in function().
3
Write the body: Code the logic inside the curly braces { }.
4
Return the result: Use return() to send back the output.
5
Test it: Call your function with different arguments and verify the output.

Example 1: Area of a Circle

Write a function that computes the area of a circle given its radius. Recall the formula: \( A = \pi r^2 \).

circle_area <- function(radius) { area <- pi * radius^2 return(area) } circle_area(5) # 78.53982 circle_area(10) # 314.1593

Example 2: BMI Calculator

A function with two parameters. BMI formula: \( \text{BMI} = \dfrac{\text{weight (kg)}}{\text{height (m)}^2} \).

calculate_bmi <- function(weight_kg, height_m) { bmi <- weight_kg / height_m^2 return(round(bmi, 1)) } calculate_bmi(70, 1.75) # 22.9 calculate_bmi(90, 1.80) # 27.8

Example 3: Conditional Return

Functions become powerful with if/else logic. Here, return() enables early exit from different branches.

check_sign <- function(x) { if (x > 0) { return("Positive") } else if (x < 0) { return("Negative") } else { return("Zero") } } check_sign(7) # "Positive" check_sign(-3) # "Negative" check_sign(0) # "Zero"

Variable Scope Inside Functions

Variables created inside a function are local: they exist only while the function runs and cannot be accessed from outside.

Global Environment x <- 10 my_func <- function(a) { ... } Local Environment (inside my_func) a <- 5 (parameter, local) result <- a * 2 (created locally) These vanish when the function ends

Common Mistakes

✕ Forgetting return()
Forgetting to provide a return value for every possible path in a conditional block, which can lead to the function returning an unexpected `NULL`.
✕ Using = instead of <-
While = works for assignment inside function(), R convention is <- for defining function names.
✕ Missing parentheses on call
Writing my_func instead of my_func() prints the source code, not the result.

Quick Reference Summary

Concept Syntax / Detail Example
Define name <- function() { } add <- function(a,b) { }
Return return(value) return(a + b)
Defaults param = default function(x, n = 2)
Call name(args) add(3, 4)
Scope Local vars are temporary Only return() passes out

Question 1 of 5

Which keyword is used to create a new function in R?

Question 2 of 5

What does this function return when called as mystery(4)?

mystery <- function(x) {
  y <- x * 3
  z <- y + 1
  return(z)
}

Question 3 of 5

If a function does not include a return() statement, what does R return?

Question 4 of 5

What happens if you try to access a variable defined inside a function from outside that function?

Question 5 of 5

Given the function below, what does power(3) return?

power <- function(base, exp = 2) {
  return(base ^ exp)
}