Does the function apply in an orderly manner?

I have a list of functions

functions <- list(f1, f2, f3, ...) 

And I need to pass the object x through all the functions. I could do this:

 for (fun in functions){ fun(x) } 

Functions do not return anything, but their order is important, i.e. f1(x) must be applied before f2(x) .

So I am thinking of using lapply :

 lapply(functions, function(fun) fun(x)) 

But I donโ€™t know if lapply first lapply first function of the functions list or if it follows a different order. With a loop, I assure the order, but it can go slower.

Any idea?

+5
source share
1 answer

The wording of the question โ€œpass x through ...โ€ suggests that you think this will perform โ€œcomposition,โ€ that is, the sequential application of functions to the results of previous applications. None of the solutions you offer will do this, although you can redo your for loop to do this. Take a look at the ?funprog man page, which I shamelessly quote in part:

 ## Iterative function application: Funcall <- function(f, ...) f(...) ## Compute log(exp(acos(cos(0)) Reduce(Funcall, list(log, exp, acos, cos), 0, right = TRUE) 

Compare the results of the for loop version with the Reduce version:

 > flist <- list(log, exp, acos, cos) > arg <- 0; for (f in flist) {arg <- f(arg)} > arg [1] 6.123234e-17 > Funcall <- function(f, ...) f(...) > ## Compute log(exp(acos(cos(0)) > Reduce(Funcall, list(log, exp, acos, cos), 0, right = TRUE) [1] 0 

This shows what <something> actually happens:

 arg <- 0; for (f in flist) {arg <- f(arg);cat(arg,"\n")} -Inf 0 1.570796 6.123234e-17 

But they do not match, since right=TRUE actually changes the order of application and explains the trivial difference in the final result. For comparison:

 arg <- 0; for (f in rev(flist)) {arg <- f(arg);cat(arg,"\n")} 
+1
source

Source: https://habr.com/ru/post/1274672/


All Articles