I'd like to feed the output of a user-defined function back to its input (a recursive map), run this iteration N times, and save the output of every iteration in a vector. This is simple to do with "for" loop
my_fun <- function(x) {x/3 +1} # a user-defined function (trivial example)
my_l <- c()
x <- 0 # initial condition
for(i in 1:10) {
x <- my_fun(x)
my_l[i] <- x
}
print(my_l)
>[1] 1.000000 1.333333 1.444444 1.481481 1.493827 1.497942 1.499314 1.499771 1.499924 1.499975
The above works but seems crude. Is there a shorter way to do it? Perhaps with tidyverse/purrr?
We can use accumulate
library(tidyverse)
accumulate(1:10, ~ my_fun(.x), .init = 1)
#[1] 1.000000 1.333333 1.444444 1.481481 1.493827 1.497942 1.499314 1.499771 1.499924 1.499975 1.499992
Or with Reduce
from base R
Reduce(function(x, y) my_fun(x), 1:10, init = 1, accumulate = TRUE)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.