R 在switch语句中计算匿名函数
假设我有这样一个代码:R 在switch语句中计算匿名函数,r,switch-statement,anonymous-function,R,Switch Statement,Anonymous Function,假设我有这样一个代码: tmp <- switch("b", a = print("foo"), b = function() paste("I want to evaluate this one!"), stop("say what now?") ) 当然,我可以预定义这个函数并在switch中传递它(在这种情况下它不是匿名的),但我想知道在switch语句中计算匿名函数是否可能和/或合理如果没有大括号
tmp <- switch("b",
a = print("foo"),
b = function() paste("I want to evaluate this one!"),
stop("say what now?")
)
当然,我可以预定义这个函数并在
switch
中传递它(在这种情况下它不是匿名的),但我想知道在switch
语句中计算匿名函数是否可能和/或合理如果没有大括号,则会调用print()
显然:
> class(tmp())
[1] "character"
> class(tmp)
[1] "function"
我想可以安排
do.call()
调用匿名函数:
tmp <- switch("b",
a = print("foo"),
b = do.call(function() paste("I want to evaluate this one!"),
list()),
stop("say what now?")
)
编辑 更简单的版本是:
tmp <- switch("b",
a = print("foo"),
b = (function() paste("I want to evaluate this one!"))(),
stop("say what now?")
)
其最终结果相同:
> tmp
[1] "I want to evaluate this one!"
如果这些都在一个函数中,
foo()
可以内联定义,因此它只在外部函数调用的执行过程中存在。正如Roman所说,您会得到一个返回的函数。如果您想要一个函数的结果,那么只需放置该函数(在您的情况下,请删除函数()
)。如果需要不同功能的组合,请将其放在括号中:
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?")
)
tmp我很难理解为什么b
不能只是粘贴(“我想计算这个!”)
,也就是说,让R来计算那个语句,以便提供一个返回的对象,该对象将被传递到tmp
?我不明白,如果最终结果是在tmp
中有评估结果,为什么要这样做?你能提供更多的信息或解释吗?好的,这是默认的行为(打印对象)。我不确定这是@aL3xa的意思。我理解Q是指如何计算和调用匿名的内联函数,以便tmp
返回Q中显示的代码中当前执行的tmp()
。他实际上希望tmp
保留调用该匿名函数的结果。当然,但我想计算函数。。。加文明白了…=)+这一个一个!我假设解决方案会非常简单,非常明显。。。我特别喜欢(tmp)(
细节…=)
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!"
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?")
)