【问题标题】:R: How to output a recursive or iterative function/map output into a vector?R:如何将递归或迭代函数/映射输出输出到向量中?
【发布时间】:2019-04-09 01:53:23
【问题描述】:

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

【问题讨论】:

    标签: r loops recursion purrr


    【解决方案1】:

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

    或与Reduce 来自base R

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

    【讨论】:

    • 太棒了!你能解释一下为什么Reduce(function(x, y) 需要y 吗?这对我来说并不明显......
    • @AgileBean。根据?Reducef- a function of the appropriate arity (binary for Reduce, unary for Filter
    • 是的,我看到了,但它有点神秘。用简单的英语来说,二进制数量如何与一个额外的 y 参数相关,该参数是如何处理的?后半部分很重要
    猜你喜欢
    • 2021-11-10
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多