R:如何将递归或迭代函数/映射输出输出为向量



我想将用户定义函数的输出反馈给它的输入(递归映射(,运行此迭代N次,并将每次迭代的输出保存在向量中。这对于"for"循环来说很简单

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

上面的方法很有效,但看起来很粗糙。有更短的方法吗?也许是tidyverse/purrr?

我们可以使用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

或来自base RReduce

Reduce(function(x, y) my_fun(x), 1:10, init = 1, accumulate = TRUE)

最新更新