Reputation: 37
I was hoping to find some help with a current issue. I've written a function (F1
), which takes as input the name of another function (F2
) and some other input. The input for F2
might differ, what I'm trying to do, is to use a list as input to F1
which than will use the list as input for F2
.
F1<-function(input.list,F2){out=F2(input.list)}
However, I would like to avoid having to extract all variables in input.list
using something like a=input.list[[1]]
, I do not want to name all possible input variables for all possible F2
in F1
, rather I would like to have the variable names in input.list
to be used directly as input for F2
.
Upvotes: 0
Views: 132
Reputation: 475
I'm not sure I completely understand what you're trying to do, but below are two examples that could point you in the right direction. The wrapper functions here supply arguments to FUN
(in your case F2
) but also take their own arguments (unique_F1_factor
).
Firstly, if you want to work with lists of arguments supplied to your wrapper F1
, then I suggest using do.call
in the body of the function, like this:
# If you want to work with lists ----
F1_list = function(input_list,unique_F1_factor,FUN) {
out = do.call(FUN, input_list)
# Do stuff in F1, e.g.:
out=unique_F1_factor*out
return(out)
}
Alternatively, you could just avoid a list altogether:
# Wrapper function ----
F1 = function(...,unique_F1_factor,FUN) {
out=FUN(...)
# Do stuff in F1, e.g.:
out=unique_F1_factor*out
return(out)
}
*Note that if using a random number generator such as rnorm
, the results will differ for do.call(rnorm, args)
and rnorm(args)
even if you specify set.seed
.
Hope this helps!
Edit
Just to clarify how you would supply arguments in each case. For F1_list
you would do:
# Example with list:
F1_list(
list(sd=1,mean=3,n=10),
unique_F1_factor = 10,
FUN = rnorm
)
If instead you want to avoid the list, do:
# Example w/o list ----
F1(
sd=1,
mean=3,
n=10,
unique_F1_factor = 10,
FUN = rnorm
)
Upvotes: 1