首页 > 解决方案 > Call function on its own output, N times

问题描述

I want to run a function N times, with it's input being the output it produced in the last iteration. Here's a manual example (with N=3):

fun <- function(data) {
  x <- data$x
  y <- data$y
  
  new_x <- x+y
  new_y <- x*y
  
  list(x=new_x, y=new_y)
}


#Initialise:
data <- list(x=2,y=3)
#Run N times:
data <- fun(data)
data <- fun(data)
data <- fun(data)

Is there a simple/fast way to do this, without using slow loops?

标签: r

解决方案


有没有一种简单/快速的方法来做到这一点

是的,这是一个简单的循环:

N = 3
for(i in 1:N) {
  data = fun(data)
}

不使用慢循环?

这并不慢。

R 中的循环比向量化操作慢。但是,由于每次迭代都依赖于先前的结果,因此无法对其进行矢量化。使用 R 的 JIT 编译,for循环可能比 R 中隐藏循环的常用方法(如*apply函数)更快。无论如何,很难让大多数 *apply 函数更新它们的输入以进行连续迭代,正如这里所需要的那样。(多年来,JIT 编译已默认启用。)


推荐阅读