rfunctional-programmingpurrrunfold

Given a vector v and fn f, how do I generate the matrix {v, f(v), f(f(v)), ... f^k(v)}?


I have a vector x and a function f. I need to generate the matrix whose first column is v, second column is f(v), and so on up to the final column f^k(v). In a functional language I could use an unfold operation. I've had a look at the purrr cheatsheet, but I can't spot any analogue.

If you need a concrete example, take v = c(1:100) and f = function(x){return (2*x)} -- but please don't exploit the fact that f^k happens to have a nice closed form in this case.


Solution

  • Are you looking for something like:

    v = c(1:100)  
    f = function(x){return (2*x)}
    
    df <- data.frame(v)
    
    for( i in 1:5) {
       df[,(i+1)] <- f(df[,i])
    }