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.
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.
Why Define Your Own Functions?
Anatomy of an R Function
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 <-.
Arguments vs Parameters
How Return Values Work
R functions can return values in two ways. Understanding both is essential for writing predictable code.
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.
How to Write a Function
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 \).
Example 2: BMI Calculator
A function with two parameters. BMI formula: \( \text{BMI} = \dfrac{\text{weight (kg)}}{\text{height (m)}^2} \).
Example 3: Conditional Return
Functions become powerful with if/else logic. Here, return() enables early exit from different branches.
Variable Scope Inside Functions
Variables created inside a function are local: they exist only while the function runs and cannot be accessed from outside.
Common Mistakes
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)
}