为什么下面的工作:
foo <- function(x) {x}
curve(foo)
# plots the identity function between 0 and 1
这不是:
curve(function(x) {x})
Error in curve(function(x) { : 'expr' did not evaluate to an object of length 'n'
还有
# the anonymous function can be called
foo(1) #1
(function(x) x)(1) #1
all.equal(foo, function(x) {x})
# TRUE
我尝试了“quote()”和“expression()”的各种组合,但没有结果。
最佳答案
实际上,curve
的帮助页面没有说“expr”参数可以是一个函数对象。接受的参数的三种类型是“函数的名称,或者作为 x 的函数编写的调用或表达式,它将计算为与 x 长度相同的对象。” (强调已添加。)
以下全部成功:
curve( (function(x) {x})(x) )
curve( local(x) )
curve( eval(x) )
当你看到...
all.equal(foo, function(x) {x})
# TRUE
...它是说附加到名称 foo
的语言对象与 function(x) {x}
相同。 (all.equal.language
函数解析对象或对象名称并比较字符结果。)
关于r - 将匿名函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33809897/