The Wayback Machine - https://web.archive.org/web/20240910021000/https://www.geeksforgeeks.org/recursive-functions-in-r-programming/
Open In App

Recursive Functions in R Programming

Last Updated : 05 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Recursion, in the simplest terms, is a type of looping technique. It exploits the basic working of functions in R. 

Recursive Function in R:

Recursion is when the function calls itself. This forms a loop, where every time the function is called, it calls itself again and again and this technique is known as recursion. Since the loops increase the memory we use the recursion. The recursive function uses the concept of recursion to perform iterative tasks they call themselves, again and again, which acts as a loop. These kinds of functions need a stopping condition so that they can stop looping continuously. Recursive functions call themselves. They break down the problem into smaller components. The function() calls itself within the original function() on each of the smaller components. After this, the results will be put together to solve the original problem. 

Example: Factorial using Recursion in R 

R




rec_fac <- function(x){
    if(x==0 || x==1)
    {
        return(1)
    }
    else
    {
        return(x*rec_fac(x-1))
    }
}
 
rec_fac(5)


Output:

[1] 120

Here, rec_fac(5) calls rec_fac(4), which then calls rec_fac(3), and so on until the input argument x, has reached 1. The function returns 1 and is destroyed. The return value is multiplied by the argument value and returned. This process continues until the first function call returns its output, giving us the final result.

Example: Sum of Series Using Recursion

Recursion in R is most useful for finding the sum of self-repeating series. In this example, we will find the sum of squares of a given series of numbers. Sum = 12+22+…+N2 

Example: 

R




sum_series <- function(vec){
    if(length(vec)<=1)
    {
        return(vec^2)
    }
    else
    {
        return(vec[1]^2+sum_series(vec[-1]))
    }
}
series <- c(1:10)
sum_series(series)


Output:

[1] 385

R




sum_n <- function(n) {
  if (n == 1) {
    return(1)
  } else {
    return(n + sum_n(n-1))
  }
}
 
# Test the sum_n function
sum_n(5) 


Output:

[1] 15

In this example, the sum_n function recursively increases n until it reaches 1, which is the base case of the recursion, by adding the current value of n to the sum of the first n-1 values.

R




exp_n <- function(base, n) {
  if (n == 0) {
    return(1)
  } else {
    return(base * exp_n(base, n-1))
  }
}
 
# Test the exp_n function
exp_n(4, 5)


Output:

[1] 1024

In this example, the base case of the recursion is represented by the exp_n function, which recursively multiplies the base by itself n times until n equals 0.
 

Key Features of R Recursion

  • The use of recursion, often, makes the code shorter and it also looks clean.
  • It is a simple solution for a few cases.
  • It expresses in a function that calls itself.

Applications of Recursion in R

  • Recursive functions are used in many efficient programming techniques like dynamic programming language(DSL) or divide-and-conquer algorithms.
  • In dynamic programming, for both top-down as well as bottom-up approaches, recursion is vital for performance.
  • In divide-and-conquer algorithms, we divide a problem into smaller sub-problems that are easier to solve. The output is then built back up to the top. Recursion has a similar process, which is why it is used to implement such algorithms.
  • In its essence, recursion is the process of breaking down a problem into many smaller problems, these smaller problems are further broken down until the problem left is trivial. The solution is then built back up piece by piece.
     

Types of Recursion in R

  1. Direct Recursion: The recursion that is direct involves a function calling itself directly. This kind of recursion is the easiest to understand.
     
  2. Indirect Recursion: An indirect recursion is a series of function calls in which one function calls another, which in turn calls the original function.
     
  3. Mutual Recursion: Multiple functions that call each other repeatedly make up mutual recursion. To complete a task, each function depends on the others.
     
  4. Nested Recursion: Nested recursion happens when one recursive function calls another recursively while passing the output of the first call as an argument. The arguments of one recursion are nested inside of this one.
     
  5. Structural Recursion: Recursion that is based on the structure of the data is known as structural recursion. It entails segmenting a complicated data structure into smaller pieces and processing each piece separately.


Previous Article
Next Article

Similar Reads

Logarithmic and Power Functions in R Programming
Logarithm and Power are two very important mathematical functions that help in the calculation of data that is growing exponentially with time. First is the Logarithm, to which the general way to calculate the logarithm of the value in the base is with the log() function which takes two arguments as value and base, by default it computes the natura
3 min read
Conversion Functions in R Programming
Sometimes to analyze data using R, we need to convert data into another data type. As we know R has the following data types Numeric, Integer, Logical, Character, etc. similarly R has various conversion functions that are used to convert the data type. In R, Conversion Function are of two types: Conversion Functions for Data Types Conversion Functi
4 min read
Poisson Functions in R Programming
The Poisson distribution represents the probability of a provided number of cases happening in a set period of space or time if these cases happen with an identified constant mean rate (free of the period since the ultimate event). Poisson distribution has been named after Siméon Denis Poisson(French Mathematician). Many probability distributions c
3 min read
Applying User-defined Functions on Factor Levels of Dataset in R Programming - by() Function
by() function in R programming is an object-oriented wrapper function which performs the provided function on factor levels of the data set passed in the arguments of function call. Syntax: by(data, INDICES, FUN) Parameters: data: represents the dataset INDICES: represents the factor list of dataset FUN: represents the function to be performed on f
1 min read
Performing Logarithmic Computations in R Programming - log(), log10(), log1p(), and log2() Functions
log() function in R Language returns the natural logarithm (base-e logarithm) of the argument passed in the parameter. Syntax: log(x) Parameter: x: Specified value. Returns: It returns the natural logarithm of the specified value, infinity for 0 and NaN for the negative value. Example 1: # R program to calculate log value print(log(1)) print(log(30
3 min read
Get Summary of Results produced by Functions in R Programming - summary() Function
summary() function in R Language is a generic function used to produce result summaries of the results of various model fitting functions. Syntax: summary(object, maxsum) Parameters: object: R object maxsum: integer value which indicates how many levels should be shown for factors Example 1: # R program to illustrate # summary function # Initializi
2 min read
Compute the Parallel Minima and Maxima between Vectors in R Programming - pmin() and pmax() Functions
pmin() function in R Language is used to return the parallel minima of the input vectors. Syntax: pmin(x1, x2) Parameters: x1: vector one x2: vector two Example 1: # R program to illustrate # pmin() function # First example vector x1 &lt;- c(2, 9, 5, 7, 1, 8) # Second example vector x2 &lt;- c(0, 7, 2, 3, 9, 6) # Application of pmin() in R pmin(x1,
1 min read
Compute Beta Distribution in R Programming - dbeta(), pbeta(), qbeta(), and rbeta() Functions
Beta Distribution in R Language is defined as property which represents the possible values of probability. This article is an illustration of dbeta, pbeta, qbeta, and rbeta functions of Beta Distribution. dbeta() Function It is defined as Beta Density function and is used to create beta density value corresponding to the vector of quantiles. Synta
2 min read
Types of Functions in R Programming
A function is a set of statements orchestrated together to perform a specific operation. A function is an object so the interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions. The function in turn performs the task and returns control to the interpreter as well as a
6 min read
Exponential Distribution in R Programming - dexp(), pexp(), qexp(), and rexp() Functions
The exponential distribution in R Language is the probability distribution of the time between events in a Poisson point process, i.e., a process in which events occur continuously and independently at a constant average rate. It is a particular case of the gamma distribution. In R Programming Language, there are 4 built-in functions to generate ex
2 min read
Gamma Distribution in R Programming - dgamma(), pgamma(), qgamma(), and rgamma() Functions
The Gamma distribution in R Programming Language is defined as a two-parameter family of continuous probability distributions which is used in exponential distribution, Erlang distribution, and chi-squared distribution. This article is about the implementation of functions of the gamma distribution. dgamma() Function The dgamma() function is used t
2 min read
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 you want to perform a certain task multiple times. In R Programming Language when you are creating a function the function name and the file in which you are creating the function need not be the same and
8 min read
Poisson Functions in R Programming
The Poisson distribution represents the probability of a provided number of cases happening in a set period of space or time if these cases happen with an identified constant mean rate (free of the period since the ultimate event). Poisson distribution has been named after Siméon Denis Poisson(French Mathematician). Many probability distributions c
3 min read
What is the Relation Between R Programming and Hadoop Programming?
The relation between R programming and Hadoop revolves around integrating R with the Hadoop ecosystem to analyze large datasets that are stored in a Hadoop environment. R, primarily used for statistical analysis and data visualization, is not inherently built for handling big data. However, when combined with Hadoop, it can leverage Hadoop's distri
3 min read
Union() & union_all() functions in Dplyr package in R
In this article, we will discuss union() and union_all() functions using Dplyr package in the R programming language. Dataframes in use: Example: R program to create data frames with college student data and display them C/C++ Code # create dataframe1 with college # 1 data data1=data.frame(id=c(1,2,3,4,5), name=c('sravan','ojaswi','bobby', 'gnanesh
2 min read
Specify Multiple Arguments in apply Functions in R
In this article, we will discuss how to specify multiple arguments in apply functions in the R programming language. apply() function is used to apply conditions to get the resultant data like mean of data, the sum of data, etc. Syntax: apply(data, margin, function, na.rm = TRUE) where, data is the input dataframemargin is used to specify the width
2 min read
Interpolation Functions in R
In this article, we will be looking towards the approx() and the aproxfun() interpolation function with working examples in the R Programming language. Approx() and Approxfun() interpolation function These functions return a list of points that linearly interpolates given data points, or a function performing the linear (or constant) interpolation.
5 min read
as.double() and is.double() Functions in R
In this article, we will discuss about as.double() and is.double() functions in R Programming Language. as.double() Method in R as.double is used to convert an integer to double. Syntax: as.double(input_values) Both will take values as input. Example: In this example, we will a vector with 5 elements and convert to double using as.double() C/C++ Co
1 min read
cumall(), cumany() & cummean() R Functions of dplyr Package
In this article, we will discuss about cumall(), cummany(), and cummean() functions in R Programming Language. Which are available in dplyr() package. We have to install and load dplyr package. Install - install.packages("dplyr") Load - library("dplyr")cumall() This function will check whether the first element is TRUE. if yes, then it will return
3 min read
apropos() and find() Functions in R?
In this article, we will be discussing the aprops() and the find() functions with these working examples in the R programming language. Functions definitions:apropos() function: This function returns a character vector giving the names of objects in the search list matching what.find() function: This returns where objects of a given name can be fou
2 min read
Model predictions to find the best model fit using the juice() and bake() functions in R
The juice() function in R Programming Language is used to extract the data from a recipe object. It is a part of the recipes package. juice() FunctionA recipe object is a data structure that represents a pre-processing pipeline. It can be used to transform data in a consistent way. The juice() function can be used to extract the data from a recipe
11 min read
Apply a Function (or functions) across Multiple Columns using dplyr in R
Data processing and manipulation are one of the core tasks in data science and machine learning. R Programming Language is one of the widely used programming languages for data science, and dplyr package is one of the most popular packages in R for data manipulation. In this article, we will learn how to apply a function (or functions) across multi
10 min read
How to Handle Invalid Argument Error in R Functions
Handling invalid argument errors in R functions involves implementing proper input validation and providing informative error messages to users. In this guide, we'll explore common practices for handling invalid argument errors, along with examples in R Programming Language. Types of errors for Invalid Argument Error in R FunctionsMissing Argument
3 min read
saveRDS() and readRDS() Functions in R
The saveRDS function is a serialization interface for single objects and it is usually used with the readRDS function. Both saveRDS and readRDS are used for saving individual R Programming Language objects to a connection usually called a file and to restore these objects under different names. saveRDS() and readRDS() Functions in RAll the interfac
7 min read
Aggregate data using custom functions using R
In this article, we will explore various methods to aggregate data using custom functions by using the R Programming Language. What is a custom function?Custom functions are an essential part of R programming, which allows users to create reusable blocks of code tailored to their specific needs. These functions encapsulate a series of operations, m
5 min read
Tidyverse Functions in R
Tidyverse is a collection of R packages designed to make data analysis easier, more intuitive, and efficient. Among the various packages within Tidyverse, several key functions stand out for their versatility and usefulness in data manipulation tasks. In this article, we'll explore some of the most essential Tidyverse functions in R Programming Lan
4 min read
Sorting, Ordering, and Ranking: Unraveling R’s Powerful Functions
R Programming Language is widely used by data scientists and analysts. This language provides various packages and libraries that are user-friendly making analysis easier. The rich set of functions this language provides helps in data manipulation and transformation. In this article, we will understand R's powerful functions and its uses. Differenc
13 min read
How to plot user-defined functions in R?
Plotting user-defined functions in R is a common task for visualizing mathematical functions, statistical models, or custom data transformations. This article provides a comprehensive guide on how to plot user-defined functions in R, including creating simple plots, enhancing them with additional features, and customizing their appearance. Overview
3 min read
How to use data.table within functions and loops in R?
data. table is the R package that can provide the enhanced version of the data. frame for the fast aggregation, fast ordered joins, fast add/modify/delete of the columns by the reference, and fast file reading. It can be designed to provide a high-performance version of the base R's data. frame with syntax and features that are optimized for large
3 min read
Getting the Modulus of the Determinant of a Matrix in R Programming - determinant() Function
determinant() function in R Language is a generic function that returns separately the modulus of the determinant, optionally on the logarithm scale, and the sign of the determinant. Syntax: determinant(x, logarithm = TRUE, ...) Parameters: x: matrix logarithm: if TRUE (default) return the logarithm of the modulus of the determinant Example 1: # R
2 min read
Article Tags :