How To Create A Function In R

Introduction

 
In this article, I will demonstrate how to create and use functions in R. A function is simply a set of statements that have been put together for the purpose of performing a specific task. With functions, a code can be broken into simpler parts which are easy to understand and maintain. R comes with many in-built functions and it also allows its users to create their own functions.
 
In R, functions are treated as objects, meaning that the R interpreter is capable of passing control to the function, together with the arguments. The function will then perform its tasks and pass control and results to the interpreter.
 

Function Definition

 
To define a function in R, we use the function keyword. It takes the syntax given below,
  1. function_name <- function(argument_1, argument_2, ...) {  
  2. Function body  
  3. }  
The following are the different parts of the function,
 
Function Name
 
This is the actual name of the function. It is stored as an object with that name in the R environment.
 
Arguments
 
Once the function has been invoked, a value will be passed to the argument. The arguments can have default values, but arguments are optional in a function.
 
Function Body
 
This is a collection of statements that define what the function will do.
 
Return value
 
This is the last expression in our function body which is to be evaluated. 
 
R allows us to define our own functions. Each user-defined function is specific to what the user needs and we can use them just like the in-built functions.
 
The example given below shows how to create and use a function in R,
  1. # A function to return the squares of numbers in a sequence.  
  2. > new.function <- function(x) {  
  3. for(j in 1:x) {  
  4. + y <- j^2  
  5. print(y)  
  6. + }  
  7. + }  
  8. >   
It will return the following output,
  1. > new.function(4)  
  2. [11  
  3. [14  
  4. [19  
  5. [116  
  6. >  
We have defined a function named new. Function that takes one argument x. The function will create a sequence from the value of this argument and get the square of each number in the sequence.
 
Here is another example,
  1. > pow <- function(a, b) {  
  2. # function to print a raised to the power b  
  3. + result <- a^b  
  4. print(paste(a,"raised to power", b, "is", result))  
  5. + }  
  6. >  
The above function will return the following output,
  1. > pow(2,3)  
  2. [1"2 raised to power 3 is 8"  
  3. >  
Above, we have defined a function named pow. The function takes two arguments, a and b. The function will then get the result of rising a to power of b. The result of this will be assigned to the variable named result.
 

Function Calls

 
We have mentioned a function call. A function call is done using the name of the function. If the function accepts arguments, then they should be passed during the function call. 
 
Let us demonstrate how a function is called in R. We will use the function we created earlier, the new.function(),
  1. # A function to return the squares of numbers in a sequence.  
  2. >   
  3. > new.function <- function(x) {  
  4. for(j in 1:x) {  
  5. + y <- j^2  
  6. print(y)  
  7. + }  
  8. + }  
  9. >  
Call the function new.function() and pass the argument 5 as an argument.
 
new.function(5)
 
The program will return the following when executed,
  1. > new.function(5)  
  2. [11  
  3. [14  
  4. [19  
  5. [116  
  6. [125  
  7. >  
Also, it is possible for us to call a function without using an argument. The example given below best demonstrates this,
  1. # A function to return the squares of numbers in a sequence.  
  2. > new.function <- function(x) {  
  3. for(j in 1:5) {  
  4. + y <- j^2  
  5. print(y)  
  6. + }  
  7. + }  
  8. >  
Call the function new.function() and pass no argument to it.
 
new.function()
 
Execution of the above program will return the following output,
  1. > new.function()  
  2. [11  
  3. [14  
  4. [19  
  5. [116  
  6. [125  
  7. >  
When calling a function, we can specify the value of the arguments using either their names or position. This means that the arguments have to be supplied in the same order that they were defined in the function, or maybe supplied in a different sequence but assigned by use of their names.
 
Consider the example given below,
  1. # A function that takes 3 arguments.  
  2. > new.function <- function(x, y, z) {  
  3. + result <- x * y + z  
  4. print(result)  
  5. + }  
  6. >  
Call the function by the position of arguments,
 
new.function(4, 3, 12)
 
Execution of the above program will give the following output,
  1. > new.function(4,3,12)  
  2. [124  
  3. >  
Calling the function by the names of arguments,
 
new.function(x = 10, y = 7, z = 2)
 
Execution of the above program will give the following output,
  1. > new.function(x = 10, y = 7, z = 2)  
  2. [172  
  3. >  
It is possible for us to have default arguments for a function. With such, we can call the function without passing arguments to it, and the default arguments will be used to provide the result.
 
At the same time, we can pass in new values and this will allow us to get another result rather than the default one.
 
Consider the example given below,
  1. # Create a function with default arguments.  
  2. > new.function <- function(x = 2, y = 6) {  
  3. + result <- x * y  
  4. print(result)  
  5. + }  
  6. >  
Call the function without passing arguments to it,
 
new.function()
 
Execution of the above program will return the following,
  1. > new.function()  
  2. [112  
  3. >  
Call the function and pass values for the arguments,
 
new.function(7,5)
 
Execution of the above program will return the following,
  1. > new.function(7,5)  
  2. [135  
  3. >  
In the first call, we did not pass arguments to the function. The default values of the arguments were used to calculate the result. In the second call to the function, we passed new values to the arguments, 7 and 5. These were used to calculate the result.
 

Return Function

 
When creating functions, we will mostly want to have the function do some processing and return some result to us. In R, we can return some result using the return() function. The function takes the syntax given below,
  1. return(expression)  
The function can return any value which is a valid R object. Let us create an example that demonstrates how to use this function,
  1. >   
  2. > checkFunc <- function(y) {  
  3. if (y > 0) {  
  4. + result <- "y is Positive"  
  5. + }  
  6. else if (y < 0) {  
  7. + result <- "y is Negative"  
  8. + }  
  9. else {  
  10. + result <- "y is Zero"  
  11. + }  
  12. return(result)  
  13. + }  
  14. >  
Let us perform sample runs by calling the checkFunction() function and pass some arguments to it. They will run as follows,
  1. > checkFunc(2)  
  2. [1"y is Positive"  
  3. > checkFunc(-3)  
  4. [1"y is Negative"  
  5. > checkFunc(0)  
  6. [1"y is Zero"  
  7. >  
If we don’t have explicit returns from any function, the value obtained from the last expression to be evaluated will be returned automatically. 
 
The following example demonstrates this,
  1. > checkFunc <- function(y) {  
  2. if (y > 0) {  
  3. + result <- "y is Positive"  
  4. + }  
  5. else if (y < 0) {  
  6. + result <- "y is Negative"  
  7. + }  
  8. else {  
  9. + result <- "y is Zero"  
  10. + }  
  11. + result  
  12. + }  
  13. >  
They will run as follows,
  1. > checkFunc(2)  
  2. [1"y is Positive"  
  3. >  
Explicit return() functions should only be used when we need to return a value immediately from a function. If it’s not the function’s last statement, it will end the function prematurely and control will shift to the place where it was called.
 
The following example demonstrates this,
  1. > checkFunc <- function(y) {  
  2. if (y > 0) {  
  3. return("y is Positive")  
  4. + }  
  5. else if (y < 0) {  
  6. return("y is Negative")  
  7. + }  
  8. else {  
  9. return("y is Zero")  
  10. + }  
  11. + }  
  12. >  
They will run as follows,
  1. > checkFunc(2)  
  2. [1"y is Positive"  
  3. > checkFunc(-3)  
  4. [1"y is Negative"  
  5. > checkFunc(0)  
  6. [1"y is Zero"  
  7. >  
In the example given above, in case the y > 0, then the function will immediately return y is Positive without going further to evaluate the rest of the function body.
 

Summary

 
In this article, I will demonstrate how to create and use functions in R. I demonstrated how to define a function, how to call a function without arguments or with arguments and pass values for the arguments. I also explained how to use predefined return function in R. Proper coding snippets along with output are provided. 


Similar Articles