Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating anonymous function(s) within switch statement

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.

like image 371
aL3xa Avatar asked Mar 05 '26 05:03

aL3xa


2 Answers

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.

like image 106
Gavin Simpson Avatar answered Mar 08 '26 21:03

Gavin Simpson


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"
like image 33
Roman Luštrik Avatar answered Mar 08 '26 21:03

Roman Luštrik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!