Table of contents
1.
Introduction
2.
What do you mean by Functions in R?
3.
Types of Functions in R
3.1.
Built-in Functions
3.2.
User-defined function
4.
How to Define Functions
5.
Calling Functions in R
5.1.
Calling without Argument
5.2.
Calling with Argument
5.3.
Calling with Default Argument
6.
Lazy Evaluation of Function
7.
Inline Functions
8.
Frequently Asked Questions
8.1.
What are the functions in R?
8.2.
How many types of functions are there in R?
8.3.
What are user-defined functions in R?
8.4.
What are built-in functions in R?
8.5.
How many data types are there in R, and which are they?
9.
Conclusion
Last Updated: Mar 27, 2024
Medium

What are the functions in R?

Author Sohail Ali
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A function is a group of statements that are put together to perform a specific task. It helps us to simplify our code by breaking it into smaller parts. We can create a function and call it multiple times as per our needs. Thus, we don't need to write the same piece of code again and again. Similarly, R provides us with the feature of functions to simplify our task.

What are the functions in R?

In this blog, we will discuss functions in R in detail. So buckle up your seatbelts, and let's start learning.

What do you mean by Functions in R?

Functions are the building blocks of any application. An R function is a section of code that can be used repeatedly. It accepts argument lists as input and returns a value. It organises the program into logical blocks of code.

function definition

Consider functions as a container to which, if we pass our input, we will get the output that we desire. For example, suppose we want to calculate the square of a number. Here, what we can do is create a function and pass the number for which we want to calculate the square and Voila! the function will give us the result.

R comes with a lot of built-in functions which provide users with various functionalities. Now you must be wondering what built-in functions are, right? For that, let us now look at the types of functions in R.

Types of Functions in R

Types of functions in R

There are mainly two types of functions in R that are:

  • Built-in function
  • User-defined function
     

Let us discuss both of them briefly.

Built-in Functions

R contains a wide variety of built-in functions in the base R package. Build-in functions are pre-defined functions available to the user in R. These functions enable the user to perform some common operations without any need to implement them. A few build-in functions in R are sum(), mean(), max(), min(), log(), etc.

Example

# Sum of three numbers
print(paste("Sum is: ",sum(3 + 4 + 5)))

# Square root of a number
print(paste("Squre root is: ",sqrt(55)))

# Absolute value of a number
print(paste("Absolute value is: ",abs(-23.5)))

# Maximum of given numbers
print(paste("Maximum value is: ",max(23, 52, 33, 44)))

# Minimum of given numbers
print(paste("Minimum value is: ",min(23, -2, 0, -8)))

 

Output

built-in functions output

Explanation

In the above example, we used a few built-in functions in R to do some most common operations for us. These functions come in very handy when we want to reduce the length of our code and keep it small and clean.

Note: In R, you can print a string and a variable together using the paste() function inside the print() function.

User-defined function

As the name suggests, these functions are created by the users. R allows us to create our own functions for some specific tasks. It allows us to make our code more readable and add modularity to our program. 

Let us now create some user-defined functions of some built-in functions available in R.

Example

#User-defined sum function
user_sum <- function(a, b, c){
    return (a + b + c)
}
#User-defined absolute function
user_abs <- function(val){
    if(val<0){
        return (val * -1)
    }else{
        return (val)
    }
}

#initialising variables
x <- 2; y <- 3; z <- 4; val <- -23.5

#Printing the results
cat('Sum of numbers is: ', user_sum(x, y, z),"\n")
cat('Absolute value is: ', user_abs(-23.5))

 

Output

user-defined function output

Explanation

In the above example, we create two functions, user_sum and user_abs, to calculate the sum and absolute value for us. You can notice that just implementing two built-in functions can take a lot of our code area. So it is recommended to use built-in functions wherever we can.

How to Define Functions

We can define functions in R using the function keyword followed by the function name and block of code inside the curly braces { }.

Syntax of a function in R:

function_name <- function ( arg1, arg2, .... ) {
    # Function body starts
    # rest of the function code
    
}

 

Description of syntax:

  • function_name: It is the name of the function you want to create.
     
  • arg1, arg2: These are the parameters you want to pass to the function.
     
  • The function keyword is necessary to define a function. You can write the logic of your program in the function body.
     

Note: The return statement at the end of your function is optional. By default, R returns the last executed output.

Calling Functions in R

Calling functions in R

In order to execute the function, we need to call a function in our program. To call the function, we need to write the function name followed by the function arguments (if required) inside the parentheses.

Syntax to call a function in R:

function_name( arg1, arg2, .... )

 

Let us create a simple function and learn to make a call to a function.

Example

# Simple R program to 
# demonstrate function call

# Function definition
solve <- function(x, y, z){
    ans = x + y * z
    print(paste("Result is:",ans))
}

#Calling the function
solve(2, 3, 5)

 

Output

function call output

Explanation

In the above example, we create a function named solve with three required arguments x, y, z. We executed the function by calling it with its name and parameters inside the parentheses.

Note: We can call a function without passing arguments to the function by using default arguments. But, the parentheses are always needed to call a function in R.

Calling without Argument

In R, we can call a function without passing any arguments to it. Here we only need to write the function name and parentheses.

Example

# Initialising a count variable
count <- 0

# Function definition
Num_caller <- function(){

    #Incrementing the count
    count <<- count + 1
  
    #Checking required conditions
    if(count == 1){
        print("First call to the function")
    }else if(count == 2){
        print("Second call to the function")
    }else{
        print("function called more than twice")
    }
}

#Calling the function without arguments
Num_caller()
Num_caller()
Num_caller()

 

Output

calling without argument output

Explanation

In the above example, we created a function Num_caller to check the number of times we called the same function. We created a global count variable to store the count of function visits and incremented it each time the function gets called. Thus, we were able to get our output without passing any parameters to the function.

Calling with Argument

Whenever we call a function using arguments, two cases are possible in that scenario.

  • Case 1: Arguments are passed in the same order as specified in the function definition.
     
  • Case 2: Arguments are passed randomly. In such cases, we should pass the arguments with their names to the function in order to avoid any confusion.
     

Now, let’s look at an example for both of the above cases.

Example

# Function definition
evaluate <- function(a, x, b){
    return  ((a*x) + b)
}

#Calling the function correct an order
res1 <- add(2, 3, 4)

#Calling the function in random order
res2 <- add(b = 4, x = 3, a = 2)

#Printing both the results
cat("First result: ", res1, "\n")
cat("Second result: ", res2)

 

Output

calling with argument output

 

Explanation

In the above example, we created a function to compute the expression for a straight line (y = mx + c). Here, we can notice that we got the same result by passing arguments in two different ways. In the first way, we passed the arguments in the specified order of the function and in the second way, we used the name of the arguments and passed them in random order.

Calling with Default Argument

We can initialise a function with some default arguments which may or may not need to be passed while calling the function. This feature is useful when you want some default values for some variable that should only be overridden by the user.

Example 

# Function definition
evaluate <- function(a=2, x=3, b=4){
    return  ((a*x) + b)
}

#Calling with no argument
print(evaluate())

#Calling with a single argument
print(evaluate(2))

#Calling with two arguments
print(evaluate(5, 4))

#Calling with three arguments
print(evaluate(2, 3, 4))

 

Output

calling with default argument output

Explanation

In the above example, we initialised the arguments a, b, and c with default values 2, 3, and 4. If a user passes an argument, that argument will be used in the function; otherwise, the function will use the default arguments in its computation.

Lazy Evaluation of Function

In R, arguments are evaluated lazily. Here, lazily means that the arguments will get used in the function whenever needed. If any argument is passed but not needed in the function body, then it will get neglected by the function. Thus, we can optimise resource utilisation and increase the function performance with this feature.

Example 1

# Function definition
my_function <- function(a, b, c) {
    result <- 2 * a + b;
    print(paste("Result is:",result))
}

# Calling the function with lazy evaluation
my_function(2, 3, 4)

 

Output

example 1 output

Explanation

In the above example, the argument c was passed while calling the function but was not needed in the function body. Thus, the argument c was not evaluated in the function computation.

Example 2

# Function definition
my_function <- function(a, b, c) {
    result <- 2 * a + b;
    print(c)
}

# Calling the function with lazy evaluation
my_function(2, 3, 4)
my_function(2,3)

 

Output

example 2 output

Explanation

In this example, we pass the argument c and use it in the function body. Thus, the argument was evaluated and printed by the R. But, in the second call, we didn’t pass argument c, and thus, the compiler threw the missing argument error.

Inline Functions

As the name suggests, these functions are written in a line. By inline, we mean that we can avoid writing the function body and write the function code just after the function arguments. However, we need to write the function keyword and arguments to create a function.

Syntax

function (arg1, arg2, … ) { expression }

 

Example

# Simple R program to 
# demonstrate inline functions

#Function definition
my_fun <- function(m, x, c) print(paste("Result is:",(m*x +c)))

#Calling the function
my_fun(2, 3, 4)

 

Output

inline example output

Explanation

In the above example, we create a function to compute a straight-line equation. You can observe that we printed the desired result just after the arguments without writing curly braces and a function body. Thus, using the inline function, we can create a tiny function to save a lot of time in loading and executing the function.

Frequently Asked Questions

What are the functions in R?

In R, functions are the block of code that perform some specific task for the user. The function takes some arguments and returns output back to the caller.

How many types of functions are there in R?

In R, there are two types of functions: user-defined and built-in functions.

What are user-defined functions in R?

The user-defined functions are the function created by the user for some specific purpose.

What are built-in functions in R?

In R, built-in functions are the pre-defined functions created for a definite task. Example of such functions are the sum(), min(), max(), mean(), abs(), etc.

How many data types are there in R, and which are they?

In R, there are mainly six data types which are numeric, logical, integer, complex, character, and raw.

Conclusion

This article discusses the concept of functions in the R Programming Language. We discussed various types and ways to call a function in R. We hope this blog has helped you enhance your knowledge about functions in R. If you want to learn more, then check out our articles.

 

And many more on our platform Coding Ninjas Studio.

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your coding ability, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Live masterclass