{"id":75753,"date":"2020-01-24T10:23:15","date_gmt":"2020-01-24T04:53:15","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=75753"},"modified":"2020-01-24T10:23:15","modified_gmt":"2020-01-24T04:53:15","slug":"recursion-in-r","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/","title":{"rendered":"What is Recursion and Recursive Function in R Programming?"},"content":{"rendered":"<p>In the <strong><a href=\"https:\/\/techvidvan.com\/tutorials\/r-functions\/\">R functions<\/a> <\/strong>tutorial, we briefly looked at recursive functions. Now, in this article, we will cover their full scope. We will study the concept of <strong>recursion<\/strong> in programming languages. We will learn what recursive functions are. And also learn where recursive functions are useful through a few examples. This tutorial is surely going to be very interesting, so, get ready!<\/p>\n<h2>What is Recursion in R?<\/h2>\n<p>Recursion, in the simplest terms, is a type of <strong>looping technique<\/strong>. It exploits the basic working of functions in R. We can call a function, declared in the <strong>global environment<\/strong> of the R session, from the global environment or the function\u2019s <strong>local environment<\/strong>.<\/p>\n<p>Recursion in R is when the function <strong>calls itself<\/strong>. This forms a loop, where every time the function is called, it calls itself again and again.<\/p>\n<h3>What are Recursive Functions?<\/h3>\n<p><strong>Recursive functions<\/strong> are functions that use the concept of recursion to perform repetitive or iterative tasks. They call themselves, again and again, this imitates a loop.<\/p>\n<p>Recursive functions need a <strong>stopping condition<\/strong> so that they do not keep looping indefinitely.<\/p>\n<h3>Why use Recursive Functions?<\/h3>\n<p>Loops increase the memory and time requirements of any program. There are many cases where using a recursive function is a better alternative than using a loop. Once a function has returned its output, its local environment is destroyed along with any temporary variables and other memory allocations. This frees up the memory used by the function.<\/p>\n<p>The same goes for recursive functions. As soon as they return the output, their local environments are destroyed, thus, freeing up the memory used by every iteration.<\/p>\n<h3>Applications of Recursion in R<\/h3>\n<p>Recursive functions are used in many efficient programming techniques like <strong>dynamic programming<\/strong> or <strong>divide and conquer algorithms<\/strong>.<\/p>\n<p>In dynamic programming, for both top-down as well as bottom-up approaches, recursion is vital for performance.<\/p>\n<p>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.<\/p>\n<p>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.<\/p>\n<p>Now, let us look at a few examples of recursive functions.<\/p>\n<h4>1. Factorial using Recursion in R<\/h4>\n<p>We can find the <strong>factorial<\/strong> of a number using recursion in <a href=\"https:\/\/www.r-project.org\/\">R<\/a> like this:<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">rec_fac &lt;- function(x){\n  if(x==0 || x==1){\n    return(1)\n  } else {\n    return(x*rec_fac(x-1))\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/01\/recursion-and-recursive-functions-in-r-rec_fac.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-75754\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/01\/recursion-and-recursive-functions-in-r-rec_fac.png\" alt=\"rec_fac() - recursion and recursive functions in r\" width=\"1299\" height=\"741\" \/><\/a><\/strong><\/p>\n<p><strong>Note:<\/strong> Here, <strong><code>rec_fac(5)<\/code><\/strong> calls <strong><code>rec_fac(4)<\/code><\/strong>, which then calls <strong><code>rec_fac(3)<\/code><\/strong> and so on until the input argument <strong><code>x<\/code><\/strong>, has reached 1. The function returns 1 and is destroyed. The return value is multiplied with <a href=\"https:\/\/techvidvan.com\/tutorials\/r-arguments\/\"><strong>argument<\/strong><\/a> value and returned. This process continues until the first function call returns its output, giving us the final result.<\/p>\n<h4>2. Sum of Natural Numbers using Recursion<\/h4>\n<p>Finding the sum of natural numbers is also a good use for recursive functions. In this example, we have naturals, a vector with 30 natural numbers (integers). The function <strong><code>sum_nat<\/code><\/strong> finds the sum of the numbers using recursion.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">sum_nat &lt;- function(vec){\n  if(length(vec)&lt;=1){\n    return(vec)\n  } else {\n    return(vec[1]+sum_nat(vec[-1]))\n  }\n}\nnaturals &lt;- c(1:30)\nsum_nat(naturals)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/01\/recursion-and-recursive-functions-in-r-sum-of-natural-numbers.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-75755\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/01\/recursion-and-recursive-functions-in-r-sum-of-natural-numbers.png\" alt=\"sum of natural numbers - recursion in R\" width=\"1299\" height=\"741\" \/><\/a><\/strong><\/p>\n<h4>3. Sum of Series Using Recursion<\/h4>\n<p>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.<\/p>\n<p style=\"text-align: left\"><strong>SUM = 1<sup>2<\/sup>+2<sup>2<\/sup>+&#8230;+N<sup>2<\/sup><\/strong><\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">sum_series &lt;- function(vec){\n  if(length(vec)&lt;=1){\n    return(vec^2)\n  }else{\n    return(vec[1]^2+sum_series(vec[-1]))\n  }\n}\nseries &lt;- c(1:10)\nsum_series(series)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/01\/recursion-and-recursive-functions-in-r-sum-of-series-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-75758\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/01\/recursion-and-recursive-functions-in-r-sum-of-series-1.png\" alt=\"sum of series - recursion in R\" width=\"1299\" height=\"741\" \/><\/a><\/p>\n<h4>4. Using Recursion to Sort a Numeric Vector<\/h4>\n<p>We can also use recursive functions to sort numeric vectors. In the following example, we split the given <strong>vector<\/strong> into two smaller ones containing elements larger than or smaller than the first element. These smaller vectors are then further sorted using the same function until the length of the vectors is 1 or 0. They are then arranged in order and returned.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">quicksort &lt;- function(vec){\n  if(length(vec)&lt;=1){\n    return(vec)\n  } else {\n    subject &lt;- vec[1]\n    predicate &lt;- vec[-1]\n    large &lt;- predicate[predicate&gt;subject]\n    small &lt;- predicate[predicate&lt;=subject]\n    large &lt;- quicksort(large)\n    small &lt;- quicksort(small)\n    return(c(small,subject,large))\n  }\n}\nquicksort(c(4,82,23,0,-15,16,31,-29))<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/01\/recursion-and-recursive-functions-in-r-quicksort.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-75757\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/01\/recursion-and-recursive-functions-in-r-quicksort.png\" alt=\"quicksort() - recursion in R\" width=\"1299\" height=\"741\" \/><\/a><\/strong><\/p>\n<p>Let us go through what exactly is happening in the above example.<\/p>\n<p><strong>Step &#8211; 1.<\/strong> The quicksort function selects the first element of the input vector and compares it with the rest of the elements.<\/p>\n<p><strong>Step &#8211; 2.<\/strong> It stores the elements larger than the subject element in the large vector and the smaller elements in the small vector.<\/p>\n<p><strong>Step &#8211; 3.<\/strong> It then calls itself to sort the large and small vectors.<\/p>\n<p><strong>Step &#8211; 4.<\/strong> This process repeats until the input vector has a length less than or equal to 1. In such a case, the function returns the input vector as it is.<\/p>\n<p><strong>Step &#8211; 5.<\/strong> The function then arranges the vector in order as shown (small, subject, large) and returns this output.<\/p>\n<p><strong>Step &#8211; 6.<\/strong> The predecessors arrange the returned output in the same order and pass it forward until the first function returns the final output.<\/p>\n<h2>Summary<\/h2>\n<p>In this tutorial, we learned about recursive functions and recursion in R. We looked at a few examples and saw how the functions called themselves to solve a part of the bigger problem.<\/p>\n<p>Recursion is the process of breaking down problems into parts to solve them. It reduces the time and space complexity of a program and makes it more efficient.<\/p>\n<p>R offers many functions like &#8211;<\/p>\n<ul>\n<li><strong><a href=\"https:\/\/techvidvan.com\/tutorials\/r-vector-functions\/\">Vector functions<\/a><\/strong><\/li>\n<li><a href=\"https:\/\/techvidvan.com\/tutorials\/r-numeric-and-character-functions\/\"><strong>Numeric and character functions<\/strong><\/a><\/li>\n<li><a href=\"https:\/\/techvidvan.com\/tutorials\/r-matrix-functions\/\"><strong>Matrix functions<\/strong><\/a><\/li>\n<\/ul>\n<p>which makes a beginner\u2019s life extremely easy.<\/p>\n<p><strong>Any difficulty while practicing recursive functions?<\/strong><\/p>\n<p>Ask our <strong>TechVidvan<\/strong> experts in the comment section below.<img decoding=\"async\" class=\"emoji tc-smart-load-skip tc-smart-loaded\" role=\"img\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/12.0.0-1\/svg\/1f642.svg\" alt=\"?\" \/><\/p>\n<p>Keep Learning!!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the R functions tutorial, we briefly looked at recursive functions. Now, in this article, we will cover their full scope. We will study the concept of recursion in programming languages. We will learn&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":75770,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1020],"tags":[1461,1462,1463,1464,1465,1466,1467,1468],"class_list":["post-75753","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-r","tag-application-of-recursion","tag-r-recursion","tag-r-recursive-function","tag-recursion-in-r","tag-recursion-in-r-programming","tag-recursive-function","tag-recursive-iteration-r","tag-why-use-recursive-functions"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>What is Recursion and Recursive Function in R Programming? - TechVidvan<\/title>\n<meta name=\"description\" content=\"Recursion in R is a process of breaking down problems into parts to solve them. In this tutorial, learn about recursion, recursive function, &amp; applications of recursion.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"What is Recursion and Recursive Function in R Programming? - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Recursion in R is a process of breaking down problems into parts to solve them. In this tutorial, learn about recursion, recursive function, &amp; applications of recursion.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-01-24T04:53:15+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/Recursion-in-R-Programming.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"What is Recursion and Recursive Function in R Programming? - TechVidvan","description":"Recursion in R is a process of breaking down problems into parts to solve them. In this tutorial, learn about recursion, recursive function, & applications of recursion.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/","og_locale":"en_US","og_type":"article","og_title":"What is Recursion and Recursive Function in R Programming? - TechVidvan","og_description":"Recursion in R is a process of breaking down problems into parts to solve them. In this tutorial, learn about recursion, recursive function, & applications of recursion.","og_url":"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-01-24T04:53:15+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/Recursion-in-R-Programming.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"What is Recursion and Recursive Function in R Programming?","datePublished":"2020-01-24T04:53:15+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/"},"wordCount":871,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/Recursion-in-R-Programming.jpg","keywords":["application of recursion","R recursion","R Recursive Function","recursion in R","recursion in R programming","recursive function","recursive iteration R","why use recursive functions"],"articleSection":["R Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/","url":"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/","name":"What is Recursion and Recursive Function in R Programming? - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/Recursion-in-R-Programming.jpg","datePublished":"2020-01-24T04:53:15+00:00","description":"Recursion in R is a process of breaking down problems into parts to solve them. In this tutorial, learn about recursion, recursive function, & applications of recursion.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/Recursion-in-R-Programming.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/Recursion-in-R-Programming.jpg","width":802,"height":420,"caption":"Recursion in R Programming"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/recursion-in-r\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"What is Recursion and Recursive Function in R Programming?"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/75753","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=75753"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/75753\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/75770"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=75753"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=75753"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=75753"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}