Can we create a 2-dimensional array for matching combinations of two function arguments?
For example, if I write a function with 1 argument (in addition to data input argument):
choose_procedure <- function(x, what_to_do) {
switch(what_to_do,
"mean" = {...}, # mean(x) or mean(x, na.rm = TRUE) or weighted.mean(x)
"median" = {...}, # median(x)
"square" = {...}, # x * x or x ^ 2
"unique" = {...}, # unique(x)
"log" = {...} # log(x) or log10(x)
)
}
I added inline comments to imply that there could be more than one choice per what_to_do
input.
When what_to_do
= "mean"
, should it be mean(x, na.rm = TRUE)
or mean(x, na.rm = FALSE)
? Likewise, when what_to_do
= "log"
, should it be log(x)
or log10(x)
? Etc.
To handle this, I thought to introduce another argument to choose_procedure()
, called "scenario"
. So if the call to choose_procedure()
is:
choose_procedure(x = mtcars$mpg, what_to_do = "log", scenario = "A")
Then it would execute log(mtcars$mpg)
.
But if the call is
choose_procedure(x = mtcars$mpg, what_to_do = "log", scenario = "B")
then it would execute log10(mtcars$mpg)
.
An example with just "log"
and "scenario"
describes a 2x2 array:
"what_to_do"
has 2 options:log()
orlog10()
"scenario"
has two options:"A"
or"B"
Clearly, this could be handled with 4 if-statements (one for each combination), but will become very difficult to program if we have more combinations (as in choose_procedure()
example I opened with).
So I have two questions:
- I'm looking for a setup that could be extended to potentially any n × n array.
- In fact, maybe there's a way to generalize to more than n × n? For example, if we have 3 arguments:
"what_do_to"
,"scenario"
,"sub_scenario"
. Etc.
Aucun commentaire:
Enregistrer un commentaire