# Define a function specifying its required and optional arguments
function_name <- function(argument1, argument2 = TRUE, ...) {
# Code block executing operations using the provided arguments
output <- argument1 + argument2 # Example computation
return(output)
}40 Function
More than 4 250 functions and 25 000 CRAN packages
A function in programming can be viewed as a generalization of mathematical functions (Chapter 8). This generalization makes programming exceptionally useful and powerful: the input (or independent variable) can be any data type, the number of arguments can be expanded as needed, and the output follows the same flexibility.
In R, a function can represent a simple mathematical operation (such as sin(), cos(), exp(), or log()), a data constructor (such as c(), matrix(), or list()), or a summary statistic (such as mean() to compute the arithmetic average). Functions exist for nearly every statistical test, figure creation, data manipulation procedure, and tools to solve equations.
When R is installed and launched, approximately 4,250 functions are immediately available. Because these base functions do not cover every specialized workflow, new functions are created continuously.
Packages are collections of functions designed to perform specific tasks; popular examples include ggplot2 for plotting graphics and vegan for community ecological analyses. Packages streamline quantitative workflows, and the vast package ecosystem represents one of R’s primary strengths.
While the exact total number of functions across all repositories is unquantified, assuming an average of 15 functions per package yields at least 379250 functions.
Functions provide powerful capabilities, but they can also present significant challenges: how to locate the required function, how to supply appropriate arguments, how to interpret output structures, and how to resolve errors.
Formal
A function is defined using the syntax function().
A function definition consists of several structural components:
Function name: An identifier assigned to the function, adhering to the standard variable naming rules outlined in Chapter 29.
Assignment operator (
<-) and keyword: The operator assigns the function object created byfunction()to the chosen name.Arguments: Variables listed inside the parentheses, separated by commas. These accept input values passed when the function is called, and may include default values (e.g.,
argument2 = TRUE).Code block: The executable statements enclosed within curly braces
{}that perform operations on the input arguments.Return output: The
return()statement, which explicitly specifies the final result or object output by the function.
Examples
Here are examples of basic mathematical functions:
# Calculate the sine of 1 radian sin(1)[1] 0.841471# Calculate the absolute value of a negative number abs(-2)[1] 2# Calculate the square root of 25 sqrt(25)[1] 5# Combine function outputs and store the result using assignment result <- sqrt(25) + abs(-2) result[1] 7Data manipulation
# Sort a numeric vector in ascending order sort(c(10, 2, 4, 2, 3.1))[1] 2.0 2.0 3.1 4.0 10.0# Sort a numeric vector in descending order sort(c(10, 2, 4, 2, 3.1), decreasing = TRUE)[1] 10.0 4.0 3.1 2.0 2.0# Sort a character vector in alphabetical order sort(c("jaojoby", "tovo j'hay", "bessa", "reko"))[1] "bessa" "jaojoby" "reko" "tovo j'hay"# Extract unique elements from a numeric vector, removing duplicate values unique(c(10, 2, 4, 2, 3.1))[1] 10.0 2.0 4.0 3.1Plotting functions
# Generate a discrete sequence of integer values from 1 to 5 indpt_variable <- 1:5 # Compute dependent values by squaring the independent variable dpt_variable <- indpt_variable^2 # Create a scatter plot with blue triangle markers plot( x = indpt_variable, # Numeric vector of x-axis values y = dpt_variable, # Numeric vector of y-axis values col = "blue", # Point color pch = 2, # Point symbol shape (2 = open triangle) type = "p" # Plot type ("p" for points) )
Modifying plot aesthetics.1
# Generate a discrete sequence of integer values from 1 to 5 indpt_variable <- 1:5 # Compute dependent values by squaring the independent variable dpt_variable <- indpt_variable^2 # Create a line plot with a red line plot( x = indpt_variable, # Numeric vector of x-axis values y = dpt_variable, # Numeric vector of y-axis values col = "red", # Line color type = "l" # Plot type ("l" for lines) )
Tips and warnings
By convention, function names in R are written in lowercase. However, the naming conventions outlined in Chapter 29 are also widely applied, such as
snake_case(e.g.,read_csv()) orcamelCase(e.g.,makeMatrix()). Additionally, many foundational functions in base R utilize aperiod.separatednaming style, such asdata.frame()orread.csv().Functions are distinguished visually and syntactically from variables by the trailing parentheses
()that follow their name. While a variable stores an object, a function represents an executable action that accepts arguments within those parentheses.The vast majority of R packages are hosted on CRAN (Comprehensive R Archive Network), the official repository that subjects packages to rigorous quality and installation checks. Other major public repositories include Bioconductor, which specializes in genomic and biological data analyses, and GitHub, which hosts developmental versions and user-contributed community packages.
Despite the large number of functions in R, a user ultimately has specific needs and it is more efficient to write a function. That’s when programming becomes more and more fun.
Bonus
The matrix() function (Chapter 36) illustrates two core principles of function construction: implicit versus explicit arguments, and arguments with versus without default values.
Inspecting the documentation for the matrix() function reveals its formal function signature and argument list:
matrix()
The function defines four primary arguments: data, nrow, ncol, and byrow.
Implicit vs explicit argument names
Consider the fruit data used in this handbook. The matrix was constructed by specifying argument names explicitly within the function call.
# Define a numeric vector of fruit counts
data_fruit <- c(6, 3, 0, 1, 3, 1, 10, 0, 0.5, 0, 0, 2)
# Construct a 4x3 matrix using explicit argument names in standard order
mat <- matrix(
data = data_fruit,
nrow = 4,
ncol = 3,
byrow = FALSE
)
mat [,1] [,2] [,3]
[1,] 6 3 0.5
[2,] 3 1 0.0
[3,] 0 10 0.0
[4,] 1 0 2.0
In the next example below, the order of the arguments was shuffled but that does not affect the output. It works because the argument names are explicitly supplied.
# Construct a matrix using explicit argument names in arbitrary order
mat <- matrix(
byrow = FALSE, # byrow is provided first
ncol = 3,
data = data_fruit,
nrow = 4
)
mat [,1] [,2] [,3]
[1,] 6 3 0.5
[2,] 3 1 0.0
[3,] 0 10 0.0
[4,] 1 0 2.0
In the next example, the argument names are omitted. Passing values without supplying explicit names relies on implicit (positional) arguments. In positional matching, R assigns input values based strictly on the order defined in the function’s formal specification.
# Construct a matrix using positional matching (data, nrow, ncol, byrow)
mat <- matrix(data_fruit, 4, 3, FALSE)
mat [,1] [,2] [,3]
[1,] 6 3 0.5
[2,] 3 1 0.0
[3,] 0 10 0.0
[4,] 1 0 2.0
Reordering positional values can result in unintended behaviors or runtime errors. A frequent source of errors is a mismatch between the expected position of an argument and the position of the value provided2.
# Alter dimensions by swapping positional arguments for nrow and ncol
mat <- matrix(data_fruit, 3, 4, FALSE)
mat [,1] [,2] [,3] [,4]
[1,] 6 1 10.0 0
[2,] 3 3 0.0 0
[3,] 0 1 0.5 2
# Attempt to pass matrix dimensions before data, resulting in a strange behavior
mat <- matrix(3, data_fruit, 4, FALSE)
mat [,1] [,2] [,3] [,4]
[1,] 3 3 3 3
[2,] 3 3 3 3
[3,] 3 3 3 3
[4,] 3 3 3 3
[5,] 3 3 3 3
[6,] 3 3 3 3
Using explicit argument names avoids this issue entirely or/and the challenge of remembering the order of each argument. However, in cases where the function’s first argument is self-evident, it is often supplied implicitly, with subsequent parameters remaining explicit.
# Pass the data vector implicitly while specifying remaining arguments explicitly
mat <- matrix(
data_fruit,
nrow = 4,
ncol = 3,
byrow = FALSE)Default argument values
- Specifying all arguments explicitly:
# Construct a matrix with all arguments defined explicitly
mat <- matrix(
data = data_fruit,
nrow = 4,
ncol = 3,
byrow = FALSE
)
mat [,1] [,2] [,3]
[1,] 6 3 0.5
[2,] 3 1 0.0
[3,] 0 10 0.0
[4,] 1 0 2.0
- Omitting arguments with default values:
When optional arguments are omitted, R uses their predefined default values. If ncol is not specified, it is automatically inferred from the length of the data vector and nrow. The byrow parameter defaults to FALSE.
# Construct a matrix using default values for ncol and byrow
mat <- matrix(
data = data_fruit,
nrow = 4
)
mat [,1] [,2] [,3]
[1,] 6 3 0.5
[2,] 3 1 0.0
[3,] 0 10 0.0
[4,] 1 0 2.0
Default argument values simplify function calls. For example, plotting functions contain over 20 optional arguments, such as point color (col) or character size (cex). Default values eliminate the need to specify every parameter explicitly when standard behavior is desired.