Q:

Use lapply for a recursion (so without a foor loop)

I'd like to solve a recursion function in R, which is defined as 
p(t) = 0.5p(t-1) + 0.2p(t-2)

for t = 3,...,100, where the initial values p(1), p(2) are given.
I know that this would be possible to solve using a for loop just like this one here: Using R to solve a recursion function
I'm wondering whether this is also possible using  the lapply() function in R? I think it should somehow be possible, but I don't know where to start. I'd appreciate any hint.

A:

Sure you can use recursive function with lapply.  
p <- function(t){
  if(t == 1){ return(1) } # arbitrary number
  if(t == 2){ return(2) } # arbitrary number

  return( 0.5*p(t-1) + 0.2*p(t-2) ) 
}

lapply(3:100, p)  

Note that it is a bad idea to use a recursive function for this problem without some sort of memoization, because it will be of exponential complexity.  
The following code works in linear time instead:  
p_tab <- c(1, 2, rep(-1, 98)) # 1 and 2 arbitrary numbers
p <- function(t){
  if(p_tab[t] != -1) return(p_tab[t])

  p_tab[t] <<- 0.5*p_tab[t-1] + 0.2*p_tab[t-2]
}

p_tab <- unlist(lapply( 1:100, p))  

p_tab will be filled with the numbers you need. p_tab[100] will be p(100) for instance, if that's the one you need.

