Functions in R are reusable blocks of code that take inputs (arguments), perform a specific task, and return an output. You define them with function() and call them by name, for example my_function(x). This article explains how functions work, how to write your own, and how to use them effectively in data analysis and programming.
What Exactly Is a Function in R?
A function is an object that contains a sequence of statements. When you call it, R executes those statements in a controlled environment. Every function has three parts: the formals (the list of arguments), the body (the code inside), and the environment (where the function looks for variables). Even simple operations like mean(x) are functions. R has thousands of built-in functions, and you can create your own to avoid repeating code.
For example, the built-in sum() adds numbers: sum(1, 2, 3) returns 6. You can inspect any function by typing its name without parentheses, e.g., mean shows the source code. Functions are first-class objects, meaning you can pass them to other functions, store them in lists, or assign them to new names.
How to Write Your Own Function
Defining a function uses the syntax function(arguments) { body }. Here is a simple example that converts Fahrenheit to Celsius:
fahr_to_celsius <- function(f_temp) {
c_temp <- (f_temp - 32) * 5 / 9
return(c_temp)
}
fahr_to_celsius(212) # returns 100
Key points:
- Assign the function to a name with
<-. - Arguments go inside
function(), separated by commas. - The body is enclosed in curly braces
{ }. - Use
return()to specify the output. If you omit it, R returns the last evaluated expression.
You can also set default values: function(x, y = 10). If you call my_func(5), y will be 10. To call with named arguments, use my_func(x = 5, y = 3). This improves readability and avoids mistakes when a function has many arguments.
Scope: Where Variables Live
Variables created inside a function are local to that function. They do not exist in the global environment after the function finishes. This is called lexical scoping. For example:
my_func <- function() {
local_var <- 100
return(local_var)
}
print(local_var) # Error: object 'local_var' not found
However, a function can read variables from its enclosing environment (the environment where it was defined). If you define a function inside the global environment, it can see global variables. But modifying a global variable inside a function requires the superassignment operator <<-, which is generally discouraged because it can lead to unexpected side effects. A better practice is to pass values as arguments and return results.
Common Ways to Use Functions
Functions are used everywhere in R:
- Data transformation:
apply(),lapply(),sapply()apply a function to each element of a list or vector. - Statistical modeling:
lm(),glm(),t.test()are functions that take data and return model objects. - Plotting:
plot(),ggplot()from the ggplot2 package. - Custom analysis: You can wrap a multi-step procedure into a single function, making your code cleaner and less error-prone.
For example, to apply a custom function to each column of a data frame, you might use lapply(df, my_func). The apply family is a core part of R’s functional programming style.
Anonymous Functions and Closures
Sometimes you need a function only once, so you can define it inline without a name. This is an anonymous function. For instance, to square each number in a list:
nums <- list(1, 2, 3)
lapply(nums, function(x) x^2)
A closure is a function that captures the environment in which it was created. This allows you to create “factory” functions that generate customized functions. Example:
power <- function(exponent) {
function(x) x^exponent
}
square <- power(2)
cube <- power(3)
square(5) # 25
cube(5) # 125
Here, square and cube remember the exponent value from when they were created. This is a powerful technique for creating flexible code.
Common Mistakes and How to Avoid Them
Beginners often run into these issues:
- Forgetting to use
return()when you need a specific value early. Without it, the function returns the last computed value, which might not be what you want. - Using a variable name that conflicts with a built-in function, e.g., naming a variable
mean. This can cause confusing errors. - Not handling missing arguments. Use
missing()or default values to avoid errors. - Assuming functions modify data in place. R is copy-on-modify; most functions return a new object. For example,
sort(x)does not changex; you must assign the result. - Overusing global variables. This makes code hard to debug. Pass everything through arguments.
To debug, use debug(my_func) or insert browser() inside the function to pause execution and inspect variables.
How to Choose Between Built-in and Custom Functions
Before writing a custom function, check if a base R or package function already does the job. For example, scale() standardizes columns, aggregate() groups data, and dplyr::mutate() creates new columns. Using well-tested built-ins reduces bugs and improves performance. Write a custom function when:
- You need to repeat a specific sequence of operations more than once.
- The operation is unique to your analysis and not covered by existing functions.
- You want to encapsulate a complex procedure for readability.
For performance-critical code, vectorized functions (like sum() over a vector) are much faster than loops. But if you must loop, consider the apply family or the purrr package from tidyverse, which offers consistent syntax.
Frequently Asked Questions
What is the difference between return() and print()?
return() sets the value that the function outputs when called. print() only displays something to the console; it does not affect the returned value. For example, f <- function() { print("hi"); return(5) } prints “hi” and returns 5. If you omit return(), the last evaluated expression is returned, but print() still just displays.
Can a function return multiple values?
Yes, by returning a list. For example, f <- function(x) { list(mean = mean(x), sd = sd(x)) }. You can then access the results with $mean or $sd. Alternatively, use c() for a vector if the outputs are all the same type.
How do I pass a function as an argument to another function?
Functions are objects, so you can pass them by name. For example, apply(x, 2, mean) passes the mean function to apply. You can also pass anonymous functions: lapply(x, function(x) x * 2).
What does ... (ellipsis) do in a function definition?
The ellipsis ... allows a function to accept an arbitrary number of additional arguments, which are often passed on to other functions. For example, my_plot <- function(x, y, ...) { plot(x, y, ...) } lets you pass extra arguments like col = "red" to plot().
Why does my function not change a data frame when I call it?
In R, arguments are passed by value (copy-on-modify). If you modify a data frame inside a function, the original remains unchanged. To update the original, you must assign the result back: df <- my_func(df). There is no built-in reference semantics.
How do I write a function that works with tidyverse (e.g., dplyr)?
Use the enquo() and !! (unquote) operators from rlang to capture column names. For example, my_summarise <- function(df, col) { col <- enquo(col); df %>% summarise(avg = mean(!!col)) }. This allows you to pass unquoted column names like my_summarise(data, price).
Related
- Refresh PivotTable Data? How to Update in Excel
- Traffic Light Print Out: What It Is & How to Read It
- How to Change Camera View in Blender (Orbit, Zoom, Pan)
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- How to Make a Function in C++ (Step-by-Step)In C++, a function is a reusable block of code that performs a specific task. You call it…
- Excel Sum Across Sheets: Formulas and 3D ReferencesTo sum the same cell across consecutive worksheets in Excel, use a 3D reference such as =SUM(Jan:Mar!B2). If…
- COUNTIF with Two Variables: How to Count with Multiple CriteriaYes, you can count with two variables in Excel, and the standard way is to use the COUNTIFS…
- Excel Index Match Multiple Criteria Non Array?Yes, you can use INDEX and MATCH with multiple criteria in Excel without entering it as an array…
- Excel ROUND: Does It Round Positive or Negative Numbers?Excel’s ROUND function rounds both positive and negative numbers to the nearest value at the specified decimal place.…
- How to Use Split Function in Power AutomateThe split() function in Power Automate breaks a string into an array of substrings based on a delimiter…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.