繁体   English   中英

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

[英]R: How to output a recursive or iterative function/map output into a vector?

我想将用户定义函数的输出反馈回其输入(递归映射),运行此迭代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 R Reduce

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM