r - 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?
解决方案
有没有一种简单/快速的方法来做到这一点
是的,这是一个简单的循环:
N = 3
for(i in 1:N) {
data = fun(data)
}
不使用慢循环?
这并不慢。
R 中的循环比向量化操作慢。但是,由于每次迭代都依赖于先前的结果,因此无法对其进行矢量化。使用 R 的 JIT 编译,for
循环可能比 R 中隐藏循环的常用方法(如*apply
函数)更快。无论如何,很难让大多数 *apply 函数更新它们的输入以进行连续迭代,正如这里所需要的那样。(多年来,JIT 编译已默认启用。)
推荐阅读
- java - 在 Android Studio 中调用 jar 库
- python - 从 Django 中的 MySQL 表数据中选择不同的对
- php - 如何循环通过 PHP 代码将 JSON 数据插入 MySQL 数据库
- javascript - 如何将 javascript 对象数组从一种格式排列到另一种格式
- php - Woocommerce 可变产品库存数量更新
- javascript - 如何使用动态输入从 Firestore 查询数据
- lua - 与 NPC 对话完成后需要更改对象的透明度
- haskell - 数据派生枚举的基数
- python - 带有大文件的 Amazon s3 上的 dask read_csv 超时
- javascript - 如何查找数组中不相交的项和子数组最快包含 200,000 个项