passing an anonymous function as argument

后端 未结 2 1325
不知归路
不知归路 2021-01-20 02:40

Why does the following work:

foo <- function(x) {x}
curve(foo)
# plots the identity function between 0 and 1

And this does not:

2条回答
  •  执笔经年
    2021-01-20 02:55

    Actually the help page for curve does not say that 'expr' argument can be a function-object. The three types of accepted argument are "name of a function, or a call or an expression written as a function of x which will evaluate to an object of the same length as x." (Emphasis added.)

    All of the following succeed:

    curve( (function(x) {x})(x) )
    curve( local(x)  )
    curve( eval(x)  )
    

    When you saw that ...

    all.equal(foo, function(x) {x})
    # TRUE
    

    ... it was saying that the language object attached to the name foo was the same as function(x) {x}. (The all.equal.language-function deparses the object(s) or object-names and compares the character results.)

提交回复
热议问题