I would like to apply the same function certain number of times on a vector using the output from the function every time.
A simplified example with a simple function just to demonstrate:
# sample vector
a <- c(1,2,3)
# function to be applied n times
f1 <- function(x) {
x^2 + x^3
}
I would like to apply f1
on a
, n
number of times, for example here lets say 3 times.
I heard purrr::reduce
or purrr::map()
might be a good idea for this but couldn't make it work.
The desired output if n = 3
would be equal to f1(f1(f1(a)))
.
Here's another way to do it with
Reduce
:setting the stage
constructing a call and evaluating it
alternative 2
alternative 3 (recursive with a global-like variable)
... or even
Let's use
Reduce
(no external library requirements, generally good performance). I'll modify the function slightly to accept a second (ignored) argument:Here's what's happening.
Reduce
:The first argument is the function to use, and it should accept two arguments. The first is the value from the previous execution of the function in this reduction. On the first call of the function, it uses the
init=
value provided.First call:
Second call:
Third call:
The second argument
1:3
is used just for its length. Anything of the proper length will work.If you don't want to redefine
f1
just for this reduction, you can always doBenchmark:
Here is an option with
accumulate
NOTE:
accumulate
is similar to thebase R
optionReduce
withaccumulate = TRUE
checking with the OP's output
Or use a
for
loop (no external libraries used)