Functions in R Programming
A function accepts input arguments and produces the output by executing valid R commands that are inside the function. Functions are useful when we want to perform a certain task multiple times.
In R Programming Language when we are creating a function the function name and the file in which we are creating the function need not be the same and we can have one or more functions in R.
Creating a Function in R Programming
Functions are created in R by using the command function(). The general structure of the function file is as follows:

Note: In the above syntax f is the function name, this means that we are creating a function with name f which takes certain arguments and executes the following statements.
Parameters or Arguments in R Functions
In programming, parameters and arguments refer to the values passed into a function. They are often used interchangeably, but there is a subtle difference:
- Parameters are the variables defined in the function definition.
- Arguments are the actual values passed to the function when it is called.
A function can have multiple parameters, and these are separated by commas within the parentheses.
Example:
add_num <- function(a,b)
{
sum_result <- a+b
return(sum_result)
}
sum = add_num(35,34)
print(sum)
Output
[1] 69
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.
Read More: R Function Parameters
Calling a Function in R
After creating a Function, we have to call the function to use it. Calling a function in R is done by writing it's name and passing possible parameters value.
Passing Arguments to Functions in R Programming Language
There are several ways we can pass the arguments to the function:
- Case 1: Generally in R, the arguments are passed to the function in the same order as in the function definition.
- Case 2: If we do not want to follow any order what we can do is we can pass the arguments using the names of the arguments in any order.
- Case 3: If the arguments are not passed the default values are used to execute the function.
Now, let us see the examples for each of these cases in the following R code:
Rectangle = function(length=5, width=4){
area = length * width
return(area)
}
# Case 1:
print(Rectangle(2, 3))
# Case 2:
print(Rectangle(width = 8, length = 4))
# Case 3:
print(Rectangle())
Output
[1] 6 [1] 32 [1] 20
Types of Function in R Language
- Built-in Function: Built-in functions in R are pre-defined functions that are available in R programming languages to perform common tasks or operations.
- User-defined Function: R language allow us to write our own function.
1. Built-in Function in R Programming Language
Built-in Function are the functions that are already existing in R language and we just need to call them to use.
Here we will use built-in functions like sum(), max() and min().
print(sum(4:6))
print(max(4:6))
print(min(4:6))
Output
[1] 15
[1] 6
[1] 4
Other Built-in Functions in R
Let's look at the list of built-in R functions and their uses:
Category | Function |
---|---|
Mathematical Functions | abs() , sqrt() , round() , exp() , log() , cos() , sin() , tan() |
Statistical Functions | mean() , median() , cor() , var() |
Data Manipulation Functions | unique() , subset() , aggregate() , order() |
File Input/Output Functions | read.csv() , write.csv() , read.table() , write.table() |
2. User-defined Functions in R Programming Language
User-defined functions are the functions that are created by the user. The User defines the working, parameters, default parameter, etc. of that user-defined function. They can be only used in that specific code.
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
Create a function that takes a single input and returns a single output. For example, a function to calculate the area of a circle:
areaOfCircle = function(radius){
area = pi*radius^2
return(area)
}
print(areaOfCircle(2))
Output
[1] 12.56637
2. Multiple Input Multiple Output
Create a function that takes multiple inputs and returns multiple outputs using a list. For example, a function to calculate the area and perimeter of a rectangle:
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 in R Programming Language
For small, quick functions, use inline functions. These are defined directly in the expression.
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
Lazy Evaluations of Functions in R Programming Language
In R, functions are executed lazily, meaning that if some arguments are missing, the function still executes as long as those arguments are not involved in the execution. For example, consider the following function Cylinder, which calculates the volume of a cylinder using diameter and length. The argument radius is defined but not used in the calculation.
Even if we don't pass the radius, the function will still execute because it doesn't affect the volume calculation.
Cylinder = function(diameter, length, radius ){
volume = pi*diameter^2*length/4
return(volume)
}
print(Cylinder(5, 10))
Output
[1] 196.3495
If we do not pass the argument and then use it in the definition of the function it will throw an error that this "radius" is not passed and it is being used in the function definition.
Example
Cylinder = function(diameter, length, radius ){
volume = pi*diameter^2*length/4
print(radius)
return(volume)
}
print(Cylinder(5, 10))
Output
Error in print(radius) : argument "radius" is missing, with no default
We have discussed all about R functions to give we some idea about using functions in R language. we can go and study each individual in-built function on this page to completely grasp the concept of R functions and their uses.
Also Check