Home > Back-end >  Combining recursion with map - is reduce the solution?
Combining recursion with map - is reduce the solution?

Time:02-04

I am trying to avoid using a for loop at all costs in this example. Consider this simple case:

I have a vector z and an initial condition b1:

z <- 1:5
b1 <- 0

Consider also this simple function like adding:

f <- function(y, b){
 return(y   b)
}

I'd like to write a function that generates a sequence S as follows: the first element, call it S[1] is f's output with the y argument as z[1] and the b argument as the initial condition b1. The second element S[2] is such that S[2] = f(y = z[2], b = S[1]). How can I?

Keep in mind that I don't want to use stuff like cumsum since my actual function f is more complicated The desired output on this case would be the vector:

c(0   1,
1   2,
3   3,
6   4,
10   5)

Or c(1, 3, 6, 10, 15)

I thought about using reduce but I guess it only accepts deals with the recursive argument b and not the mapping part y

CodePudding user response:

Reduce(function(prev, this) prev   this,
       1:5, init=0, accumulate=TRUE)[-1]
# [1]  1  3  6 10 15

You can easily use your own function in place of my anonymous function, I defined it like that to demonstrate which value is which: the first argument is your S[n-1], the second is your z[n].

The [-1] is because of this: without init=, the first call to function is effectively f(prev=z[1], this=z[2]), which is correct only when your b1 is 0. If b1 is ever anything else, then you must use init=b1. However, when using init=, it effectively prepends it to the input vector (your z). This means that the first call to the function is f(prev=b1, this=z[1]) which is right, but it also means that the return value includes b1 and is therefore too long. Fortunately, we can drop the first element very easily.

Lastly, the normal operation of Reduce is to only return the value from the last call to the function (ergo the reduction concept of Reduce); using accumulate= really means Reduce is a cumulative-operation function.

  •  Tags:  
  • Related