Ira*_*kli 2 recursion loops r purrr
我想将用户定义函数的输出反馈回其输入(递归映射),运行此迭代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
Run Code Online (Sandbox Code Playgroud)
上面的作品,但似乎很粗糙。有更短的方法吗?也许有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
Run Code Online (Sandbox Code Playgroud)
或Reduce从base R
Reduce(function(x, y) my_fun(x), 1:10, init = 1, accumulate = TRUE)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
133 次 |
| 最近记录: |