I am writing a wrapper function where I am linking multiple steps of a pipeline. I would like to make it so the user can input multiple options where the value would be input if present, and the default of the paernt function otherwise.
For example
orig_func1 <- function(num = 1, x=3, y=2){
num <- (x y)/num
return(num)
orig_func2 <- function(num = 1, z=5, w=23){
num <- (z - w)/num
return(num)
now I want to create a wrapper to perform each of these a specified amount of times. I want num to change with each iteration as an input for the next function
wrapper <- function(
num = 1,
steps = list(c(step = NULL, x = NULL, y = NULL),
c(...),...){
for (i in 1:length(steps)){
if (steps[[i]]['step'] == "orig_func1"){
num <- orig_func1(num = num, x = steps[[i]][['x']], y = steps[[i]][['y']]
}
if (steps[[i]]['step'] == "orig_func2"){
num <- orig_func2(num = num, z = steps[[i]][['z']], y = steps[[i]][['z']]
}
}
If for example I tried to run this
test <- (
num = 1,
steps = list(c(step = orig_func1, x = 2, y = 5),
c(step = orig_func2, z = 4, w = 6),
c(step = orig_func1, x = 2) # I want default for y in this case
Lets say I try to run this while leaving y blank for the third step because I want default, this would throw an error because steps[[i]][['y']] wont be found. How can I make it so the default of the parent function is used if not present in the step list without respecifiying the defaults in the wrapper?
CodePudding user response:
Your code isn't particularly clear and has many errors so it is hard to see exactly what you're trying to do - for example you aren't returning the numbers you calculate anywhere so the output of your wrapper function will always be NULL.
I think what you're trying to do can be solved by using base::do.call
to supply the arguments as a list rather than individually extracting them as you've done.
Something like this:
wrapper <- function(num = 1,
steps = list()){
for (i in 1:length(steps)){
step_func <- steps[[i]][["step"]] # get function from 'step' element
step_args <- steps[[i]][-1] # remove 'step' element
num <- base::do.call(step_func, step_args) # call function with arguments
}
}