2

Currently I'm working on a R project which includes following code.

vec <- 1:25
fib <- function(x)
{ if (x==0) return (0)
 if (x==1) return (1)
 if (x==2) return(2)
 return(fib(x-1)+fib(x-2))
}
lapply(vec,fib)

I just want to know that, how does R compute the fibonacci function in a code like this? More simply, when it comes to number 25 in vector "vec" does R compute the whole function, or can R compute the fib(25) using the values of fib(24) and fib(23) since they have been computed already?

Psidom
  • 209,562
  • 33
  • 339
  • 356
Hansy Kumaralal
  • 169
  • 3
  • 13
  • 1
    See [here](http://stackoverflow.com/questions/6807068/why-is-my-recursive-function-so-slow-in-r) a similar post. – alexis_laz Sep 21 '16 at 15:16

1 Answers1

2

It will compute all the recursive values one by one by default, but you can use an external package like memoise to cache previous values, or do it yourself. Have a look at the following blog which shows this using a Fibonacci function as well.

AlvaroP
  • 390
  • 1
  • 2
  • 9