r - Calling functions from a list recursively -


i writing program in need function call function determined in period beforehand, may again call function determined before , on. however, finding myself inable implement in r.

here minimal example of trying do:

functions <- list() functions[[1]] <- function(x){   x }  (i in 2:10) {   functions[[i]] <- function(x){     functions[[i-1]](x) + x   } } 

so after running script, want happen when call functions[[10]](1) r determines value function have had in period 9, needs value of function in period 8 , on , adds input it. (so obviously, output should 10).

the problem when this, function calls infinitely. list looks this:

[[1]] function (x)  {     x }  [[2]] function (x)  {     functions[[i - 1]](x) + x }  [[3]] function (x)  {     functions[[i - 1]](x) + x }  (...) 

so when call functions[[10]](x), evaluates functions[[9]](x) + x, functions[[9]] keeps calling on , on again.

is there can force r write value of i - 1 each element of list, such follows?

[[1]] function (x)  {     x }  [[2]] function (x)  {     functions[[1]](x) + x }  [[3]] function (x)  {     functions[[2]](x) + x }  (...) 

or there other way trying here?

(obviously, in above given example, sum, in application trying simulate here, not possible , can't think of way other having each function call 1 before it).

here go

functions <- list() functions[[1]] <- function(x){     x }  (i in 2:10) {     functions[[i]] <- function(x,i){         functions[[i-1]](x) + x     }     formals(functions[[i]])$i <- } functions[[10]](5)  # 50 

Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -