在其自身的输出上重新循环一个函数 [英] Relooping a function over its own output
本文介绍了在其自身的输出上重新循环一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经定义了一个函数,希望多次将其重新应用于其自身的输出.我尝试过
I have defined a function which I want to reapply to its own output multiple times. I tried
replicate(1000,myfunction)
,但意识到这只是将我的函数应用到我的初始输入中1000次,而不是每次都将我的函数应用到新输出中.实际上,我想要的是:
but realised that this is just applying my function to my initial input 1000 times, rather than applying my function to the new output each time. In effect what I desire is:
function(function(...function(x_0)...))
1000次以上,并且能够在每个阶段看到更改.
1000 times over and being able to see the changes at each stage.
我之前已将b定义为某个长度为7的向量.
I have previous defined b as a certain vector of length 7.
b_0=b
C=matrix(0,7,1000)
for(k in 1:1000){
b_k=myfun(b_(k-1))
}
C=rbind(b_k)
C
这是我想要的背后的正确主意吗?
Is this the right idea behind what I want?
推荐答案
在这里循环就可以了.
apply_fun_n_times <- function(input, fun, n){
for(i in 1:n){
input <- fun(input)
}
return(input)
}
addone <- function(x){x+1}
apply_fun_n_times(1, addone, 3)
给出
> apply_fun_n_times(1, addone, 3)
[1] 4
这篇关于在其自身的输出上重新循环一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文