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:
tmp <- switch("b",
a = print("foo"),
b = do.call(function() paste("I want to evaluate this one!"),
list()),
stop("say what now?")
)
e.g.:
> tmp
[1] "I want to evaluate this one!"
Edit A simpler version of the above is:
tmp <- switch("b",
a = print("foo"),
b = (function() paste("I want to evaluate this one!"))(),
stop("say what now?")
)
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:
foo <- function() paste("I want to evaluate this one!")
tmp <- switch("b",
a = print("foo"),
b = foo(),
stop("say what now?")
)
Which has the same end result:
> tmp
[1] "I want to evaluate this one!"
If this is all within a function, foo() could be defined inline so it only exists during the execution of the outer function call.
From what I recall, writing your object (be that data.frame, a list or as in your case, a function) without braces evokes print().
Obviously:
> class(tmp())
[1] "character"
> class(tmp)
[1] "function"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With