Let's say I have some variable funcorder
and n functions func1
, func2
, func3
up to funcn
. If funcorder=c(3,2,5...1)
where length(funcorder)==n
then I want to run my functions according to funcorder
ie.
func3
func2
func5
...
func1
If this were a smaller example, say 2 functions then I could do something like
if (identical(funcorder,c(1,2)) {
func1()
func2()
} else {
func2()
func1()
}
but this doesn't seem very elegant and definitely doesn't scale. Is there a better way?
CodePudding user response:
We may use compose
from purrr
library(purrr)
compose(!!!list(func1, func2, func3)[funcorder], .dir = "forward")(v1)
where 'v1' is the object to be executed with the functions in the order specified by funcorder
CodePudding user response:
You can have do.call
call the functions inside lapply
:
x <- 0
add1 <- function() x <<- 10*x 1
add2 <- function() x <<- 10*x 2
add3 <- function() x <<- 10*x 3
add4 <- function() x <<- 10*x 4
add5 <- function() x <<- 10*x 5
flist <- list(add1, add2, add3, add4, add5)
funcorder <- sample(1:5)
invisible(lapply(flist[funcorder], do.call, list()))
x
#> [1] 34512
funcorder
#> [1] 3 4 5 1 2
Found where I've seen this before: https://stackoverflow.com/a/7773454/9463489