Does R have a built-in function to iterate a function n times?
Suppose I have a variable x
and a function f
. I would like to execute f
on x
, then again the result, n
times.
I created a simple function for this:
iterate <- function(x, f, n) {
assertthat::assert_that(n >= 0)
if (n > 0) {
for (i in 1:n) {
x <- f(x)
}
}
x
}
Which works like this:
iterate(256, f = sqrt, n = 3)
Is this already built into R?
source to share
You can do this with a package-in Reduce
and Compose
out-of- package functional programming approach functional
. The idea is to create a list of the functions you want and link them with Compose
. You simply apply this function to x
then.
x = 256
n = 3
f = sqrt
library(functional)
Reduce(Compose, replicate(n, f))(x)
#[1] 2
Or use freduce
from magrittr
:
library(magrittr)
freduce(x, replicate(n, f))
#[1] 2
source to share