Functions In R Programming

The concept of a function is similar in the R programming language as in any other programming language such as C, C++, Java, PYTHON, etc. In this tutorial, you will learn the purpose of functions in R, how it is used for building a simple and efficient program, and their different types to execute logic.

What is a function in R?

A function is a set of reusable codes to execute logic. In R programming language a function is treated as an R object.

When a program begins its execution the interpreter passes the flow of control to the function with the arguments needed to execute the codes. Once completing the successful execution of the function the control passes back to the interpreter.

add function img

Need of function in R

A function is used when there is a need to apply the same code for different inputs. The function in R is the set of instructions that are applied to these R objects. A function saves the time of a programmer by avoiding the repetition of codes to execute the same logic. In other words, writing the same code, again and again, can be avoided by using functions. While using a function the inputs only vary but the functionality or code remains the same.

types of fn img

There are two types of functions introduced within R programming. They are

  1. Built-in function
  2. User-defined function

How to create a function in R?

A function is the set of instructions to execute for a similar logic but their intake of inputs differs which results in generating various outputs. A function can be used multiple times to generate an output with different input and thus saves the user time by eliminating or rewriting the same codes inside the programs repeatedly. Whenever there is an urge to perform a set of operations frequently simply call the predefined function to make it simple and easy.

In R programming a function is created using an in-build reserved word known as function.

To create a function in R

Syntax


Function_name = function(arguments){
        #body_of_function
        ……..
        return(return)
}

Where

  • function_name is the name provided to remember the function as well as the name used while calling the function which is stored in the R environment as an object.
  • function() is the reserved word and built-in function opted to create a set of reusable codes.
  • arguments are the input to the functions like arg1,arg2, etc. They are optional and may or may not contain a function. The arguments are the values passed when a function is invoked.
  • body_of_function A set of instruction to execute when the function() is called.
  • return()  is the another built-in  function  to return the value after execution of function(output).

The “function” is the reserved word that defines writing a function() in R. The function() takes input values given as arguments and begins executing the function body to achieve a specific task and returns the final result using the return() function. The function() is assigned to a variable function_name which is called when the function() needs to be executed from anywhere in the program.

Let us understand the function concept with a simple R program to add two numbers


#To create a function named add
add <- function(x, y){       #function()
  # function to add x and y
  sum <- x+y                 #function body
  return(sum)                #return()
  }

add(4,5)    #function(4,5),sum <- 4+5,return(9)
            #outputs 9

The function_name “add” takes input values as arguments arg1=4,arg2=5 like, add(4,5) which invokes the function named add and passes the arguments to the function(), the body of the function that has the collection of instructions starts to execute to evaluate the result. In our example add(4,5) invokes the function() to implement the addition of these two numbers (sum<-4+5) and is stored in another variable sum and a return() function returns the sum as output which is equal to 9 a and gets outputted in the console as shown in below


> add(4,5)
[1] 9

If the same function() named sum is called with another set of arguments as inputs, the same procedure follows and outputs the result. For example, if you call function add(234,56), it provides a result of 290.


> add(234,56)    #function(234,56),sum<-234+56,return(290)
[1] 290

Here shows the need or importance of functions in R. If a set of pre-defined code is written we can make use of it multiple times whenever required in the program with our input requirement. That makes the coding easy and saves the time needed by a programmer.

Check the screenshot in RStudio with multiple add() functions.

add fn screeshot

Let us try doing the same action of adding numbers using the function but without the return() function

Program to create a function without return() function


add <- function(x, y) {
  # function to add x and y
  sum <- x+y
  print(paste(x,"+",y, "=",sum))
}

add(4,5)

The above code also generates the same output as we discussed in our previous example. The only difference you can find is the return() function is missing instead a print statement to display the result is provided.

The result after executing this block of codes is


[1] "4 + 5 = 9"

We can infer that the return statement which is a component that constitutes the function is optional likewise some others are also.

NOTE:

  • Function name, function(),arguments, body_of_function, return()  constitutes the components of a function.
  • The function may or may not have these components, some are optional.
  • The syntax resembles a user-defined function in R.

 

What are the main components of a function in R?

The main components or parts of a function in R are generalized into three parts. They are

  1. Function body  : body()
  2. The formals      : formals()
  3. The environment: environment()
add function img

These are the components that a function in an R program constitutes which can be identified using some built-in function defined in the R program.

  • body(): The function body() with the name of the function inside the parentheses () allows identifying the set of instructions that a function is enclosed inside the curly braces.

    Example

    
    > body(add)
    {
        sum <- x + y
        print(paste(x, "+", y, "=", sum))
    }
    
    
  • formals() : The function formals() with function name inside the parentheses () identifies the list of arguments passed to the function.

    Example

    
    > formals(add)
    $x
    $y
    
    
  • environment() : The function environment() retrieves the nature functions variables.

    Example

    
    > environment(add)
    < environment: R_GlobalEnv >
    
    
add function img
Components Of R  function   Functions to check components   Description
  Function body     body() The collection of instructions inside a function to be executed defines the body of a function
  The formals     formals() The formals define the list of arguments such as arg1, arg2, arg3..etc passed to invoke a function when a function is called.
  The environment     environment() The environment defines the functions variable’s location where they are stored as R objects.

How do apply functions to R objects?

An object in R is the data with different attributes and structures in R programs.

Consider the creation of an R object named my_age which is assigned with some values by using any of the assignment operators (=,<-,->) in R. When you run the code in RStudio you can see the variable my_age gets stored as an object in the global environment.

obj creation snippet

Now consider there is another object age which is assigned a value of 4. Let us see how to apply functions to objects we created. Suppose you need to perform addition upon the objects or variables (my_age, age) you created. It is simple by adding the sum() function in R.

Use the function sum() to perform addition and pass the arguments inside the sum() function.


>  #use function sum()
> sum(my_age,age)
[1] 16

You get the output after the addition of the values stored in variables by using function sum.