Relooping a function over its own output

社会主义新天地 提交于 2019-12-24 14:24:22

问题


I have defined a function which I want to reapply to its own output multiple times. I tried

   replicate(1000,myfunction)

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 times over and being able to see the changes at each stage.

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?


回答1:


A loop would work just fine here.

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)

which gives

> apply_fun_n_times(1, addone, 3)
[1] 4



回答2:


You could use Reduce for this. For example

add_two <- function(a) a+2
ignore_current <- function(f) function(a,b) f(a)

Reduce(ignore_current(add_two), 1:10, init=4)
# 24

Normally Reduce expects to iterate over a set of new values, but in this case I use ignore_current to drop the sequence value (1:10) so that parameter is just used to control the number of times we repeat the process. This is the same as

add_two(add_two(add_two(add_two(add_two(add_two(add_two(add_two(add_two(add_two(4))))))))))



回答3:


Pure functional programming approach, use Compose from functional package:

library(functional)

f = Reduce(Compose, replicate(100, function(x) x+2))
#> f(2)
#[1] 202

But this solution does not work for too big n ! Very interesting.




回答4:


you can try a recursive function:

rec_func <- function(input, i=1000) {
                if (i == 0) {
                   return(input)
                } else {
                   input <- myfunc(input)
                   i <- i - 1
                   rec_func(input, i)
                }
            }

example

myfunc <- function(item) {item + 1}
> rec_func(1, i=1000)
[1] 1001


来源:https://stackoverflow.com/questions/29237136/relooping-a-function-over-its-own-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!