In R programming, functions are used to organize code into reusable and manageable units. A function accepts input arguments, executes the R commands inside it and produces an output. They are useful when a task needs to be performed multiple times, helping make programs more efficient and easier to understand.
- Functions can accept input values, called parameters to work with different data.
- They execute the R commands defined inside them and can return a result.
- Functions are only executed when they are called, allowing you to control program flow.

In R, you can create custom functions to perform specific tasks by defining a block of code and assigning it a name. Once defined, the function can be called multiple times with different inputs. The function() keyword is used to create a new function in R.
Parameters or Arguments
Functions are used to perform specific tasks and the values they operate on are provided through parameters and arguments. Although these terms are often used interchangeably, they have distinct meanings:
- Parameters: Variables that are defined in the function declaration. They act as placeholders for the values the function will use.
- Arguments: Actual values passed to the function when it is called. These values replace the parameters during execution.
A function can have multiple parameters and these are separated by commas within the parentheses.
Example: Adding Two Numbers Using a Function
Here we defines a function add_num that takes two numbers as input, adds them and returns the result.
add_num <- function(a, b) {
sum_result <- a + b
return(sum_result)
}
sum <- add_num(35, 67)
print(sum)
Output:
[1] 102
Here:
- a and b are parameters.
- 35 and 67 are arguments passed to the function.
Function Parameter Rules
- Number of Parameters: A function should be called with the correct number of parameters. If the number doesn't match, an error occurs.
- Default Parameter Values: Some functions have default values for parameters. If no argument is passed, these defaults are used.
- Return Value: The return() function sends the result back from the function.
Calling a Function
After defining a function, we call it by writing the function name followed by parentheses () and passing the required arguments inside the parentheses.
Case 1: Positional Arguments (Order-Based)
Arguments are passed in the same order as defined in the function
Rectangle <- function(length = 5, width = 4) {
area <- length * width
return(area)
}
print(Rectangle(2, 3))
Output:
[1] 6
Case 2: Named Arguments (Order Does Not Matter)
Arguments are passed using parameter names, so order is not important.
print(Rectangle(width = 8, length = 4))
Output:
[1] 32
Case 3: Default Arguments
If no arguments are supplied, the default values defined in the function are used.
print(Rectangle())
Output:
[1] 20
Types of Functions in R Language
In R, functions are categorized into two main types:
1. Built-in Functions
Built-in functions are pre-defined functions that come with R. They are ready to use and help perform common mathematical, statistical, data manipulation and file operations.
Example 1 : Using Built-in Functions
Here we use built-in R functions can calculate the sum, maximum and minimum values of a sequence of numbers.
print(sum(4:6))
print(max(4:6))
print(min(4:6))
Output:
[1] 15
[1] 6
[1] 4
Example 2 : Statistical Built-in Function
Here we creates a numeric vector and calculates its mean and standard deviation using built-in statistical functions in R.
nums <- c(10, 20, 30, 40)
print(mean(nums))
print(sd(nums))
Output:
[1] 25
[1] 12.90994
Common Built-in Functions in R
Category | Functions |
|---|---|
Mathematical | abs(), sqrt(), round(), exp(), log(), cos(), sin(), tan() |
Statistical | mean(), median(), cor(), var(), sd() |
Data Manipulation | unique(), subset(), aggregate(), order(), sort() |
File Input/Output | read.csv(), write.csv(), read.table(), write.table() |
2. User-defined Functions in R
User-defined functions are created by the programmer using the function() keyword. They allow customization of logic, parameters and default values.
Example 1: Even or Odd Function
Here we creates a user defined function that determines whether a number is even or odd and then prints the result for two values.
evenOdd <- function(x) {
if (x %% 2 == 0) {
return("Even")
} else {
return("Odd")
}
}
print(evenOdd(4))
print(evenOdd(3))
Output:
[1] "Even"
[1] "Odd"
R Function Examples
Now let's look at some use cases of functions in R with some examples.
1. Single Input Single Output
A function is defined to compute the area of a circle for a given radius and display the result.
areaOfCircle = function(radius){
area = pi*radius^2
return(area)
}
print(areaOfCircle(2))
Output:
[1] 12.56637
2. Multiple Input Multiple Output
In this program, the function accepts two values as input and calculates both the area and perimeter of a rectangle. The results are returned together as a list.
Rectangle = function(length, width){
area = length * width
perimeter = 2 * (length + width)
result = list("Area" = area, "Perimeter" = perimeter)
return(result)
}
resultList = Rectangle(2, 3)
print(resultList["Area"])
print(resultList["Perimeter"])
Output:
$Area
[1] 6
$Perimeter
[1] 10
3. Inline Functions
Here inline function is defined in a single line to compute a mathematical expression and the function is evaluated for different input values.
f = function(x) x^2*4+x/3
print(f(4))
print(f(-2))
print(0)
Output:
[1] 65.33333
[1] 15.33333
[1] 0
4. Passing Functions as Arguments
In R, a function can be passed as an argument to another function, allowing flexible and reusable code. This supports functional programming by enabling operations to be performed dynamically.
operate <- function(x, y, func) {
func(x, y)
}
add <- function(a, b) {
a + b
}
multiply <- function(a, b) {
a * b
}
print(operate(3, 4, add))
print(operate(3, 4, multiply))
Output:
[1] 7
[1] 12
Lazy Evaluations of Functions
Lazy evaluation in R means that function arguments are evaluated only when they are actually used inside the function. If an argument is not required in the computation, the function can still run without it. An error occurs only when a missing argument is used in execution.
Example 1: Unused Argument Does Not Cause Error
Here the argument radius is defined but not used in the calculation, so the function executes successfully even if it is not passed.
Cylinder = function(diameter, length, radius ){
volume = pi*diameter^2*length/4
return(volume)
}
print(Cylinder(5, 10))
Output:
[1] 196.3495
Since radius is not used inside the function, R does not evaluate it and no error occurs.
Example 2: Using a Missing Argument Causes Error
Here, the argument radius is used inside the function but not provided during the function call.
Cylinder = function(diameter, length, radius ){
volume = pi*diameter^2*length/4
print(radius)
return(volume)
}
print(Cylinder(5, 10))
Output
Error in Cylinder(5, 10): argument "radius" is missing, with no default
Traceback:
1. Cylinder(5, 10)
2. print(radius)
Because radius is referenced but not supplied, R evaluates it and throws an error.