Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 12 / 68

Recursive functions

This lesson covers writing a recursive function in R, with the aim of understanding how a function can call itself.

A recursive function is one that calls itself. It suits work that repeats the same pattern of calculation, such as "n! = n ร— (n-1)!".

In the sample code, factorial_r calls itself as n * factorial_r(n - 1) to calculate 5 factorial. The finishing condition if (n <= 1) return(1) is what makes the calls stop somewhere.

A common early stumble is forgetting the finishing condition. Without one, the function calls itself forever and the program dies.

In professional work, vector arithmetic or sapply is often faster than recursion in R, so it pays to choose according to the situation.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)