Say I have a code like this:
tmp <- switch("b",
a = print("foo"),
b = function() paste("I want to evaluate this one!"),
stop("say what now?")
)
Now, if I type tmp I get an unevaluated function, so I have to do add a pair of brackets afterwards in order to evaluate it:
tmp
## function() paste("I want to evaluate this one!")
tmp()
## [1] "I want to evaluate this one!"
Of course, I can predefine this function and pass it within switch (in that case it’s not anonymous), but I want to know if it’s possible and/or reasonable to evaluate anonymous function within switch statement.
I suppose one could arrange for
do.call()to call the anonymous function:e.g.:
Edit
A simpler version of the above is:
So the anonymous function is created in the first set of parentheses and the resulting function is called by appending the second set of
().But it seems cleaner to me to turn the anonymous function into a named function and call it:
Which has the same end result:
If this is all within a function,
foo()could be defined inline so it only exists during the execution of the outer function call.