First of all, if you need an efficient implementation, use the R factorial function. Do not write yourself. Then factorial is a good exercise for understanding recursion:
myfactorial <- function(n) { if (n == 1) return(1) n * myfactorial(n-1) } myfactorial(10)
Using this function memoization is useful if you intend to reuse this function. You can implement memoization in R using closure. Hadley explains this in his book .
createMemFactorial <- function() { res <- 1 memFactorial <- function(n) { if (n == 1) return(1)
It's faster?
library(microbenchmark) microbenchmark(factorial(10), myfactorial(10), memFactorial(10)) #Unit: nanoseconds # expr min lq mean median uq max neval cld # factorial(10) 235 264.0 348.02 304.5 378.5 2463 100 a # myfactorial(10) 4799 5279.5 6491.94 5629.0 6044.5 15955 100 c # memFactorial(10) 950 1025.0 1344.51 1134.5 1292.0 7942 100 b
Please note that microbenchmark evaluates features (default) 100 times. Since we saved the value for n = 10 when testing memFactorial , we will only consider if conditions and the search here. As you can also see, the R implementation, which is mostly written in C, is faster.
In a better (and more convenient) example, Fibonacci numbers are implemented. Here, the algorithm itself benefits from memoization.
#naive recursive implementation fib <- function(n) { if(n == 1 || n == 2) return(1) fib(n-1) + fib(n-2) }
Rolling
source share