Evaluating Anonymous Functions in a Switch Statement

Let's 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 invaluable function, so I need to add a couple of brackets 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 to switch(in this case, it is not anonymous), but I want to know if it is possible and / or reasonable to evaluate the anonymous function in the expression switch.

+3
source share
3 answers

I assume that one could do.call()call an anonymous function:

tmp <- switch("b",
              a = print("foo"),
              b = do.call(function() paste("I want to evaluate this one!"), 
                          list()),
              stop("say what now?")
)

eg:.

> tmp
[1] "I want to evaluate this one!"

Edit A simpler version is higher:

tmp <- switch("b",
              a = print("foo"),
              b = (function() paste("I want to evaluate this one!"))(),
              stop("say what now?")
)

, , ().


:

foo <- function() paste("I want to evaluate this one!")
tmp <- switch("b",
              a = print("foo"),
              b = foo(),
              stop("say what now?")
)

:

> tmp
[1] "I want to evaluate this one!"

, foo() , .

+2

, , ( data.frame, , ) print().

:

> class(tmp())
[1] "character"
> class(tmp)
[1] "function"
+1

, . , ( function()). , :

tmp <- switch("b",
              a = print("foo"),
              b = {
                    x <- paste("I want to evaluate this one!")
                    x <- paste(x,sample(1:10,1))
                    print(x)
              },
              stop("say what now?")
)

, , sample.

+1

Source: https://habr.com/ru/post/1794726/


All Articles