passing an anonymous function as argument

后端 未结 2 1322
不知归路
不知归路 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 03:07

    ?curve states that expr (the first argument) should be the name of a function, a call or an expression written as a function of x which will evaluate to an object of the same length as x.

    Thus, curve({x}) will yield the expected result.

    As to why curve(function(x){x}) returns an error, reading the code of curve will help. At the end of the function definition, we have :

    y <- eval(expr, envir = ll, enclos = parent.frame())
        if (length(y) != length(x)) 
            stop("'expr' did not evaluate to an object of length 'n'")
    

    and we have :

    eval(function(x){x})
    # function(x){x}
    

    and x is defined in the function code as seq.int(0, 1, length.out = 101).

    So with the call we have the error as the eval as a length of 1 which is not what we wanted.

提交回复
热议问题