asachet
asachet

Reputation: 6921

passing an anonymous function as argument

Why does the following work:

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

And this does not:

curve(function(x) {x})

Error in curve(function(x) { : 'expr' did not evaluate to an object of length 'n'

And yet

# the anonymous function can be called 
foo(1) #1
(function(x) x)(1) #1


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

I tried various combinations of "quote()" and "expression()" with no results.

Upvotes: 4

Views: 624

Answers (2)

etienne
etienne

Reputation: 3678

?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.

Upvotes: 3

IRTFM
IRTFM

Reputation: 263331

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.)

Upvotes: 5

Related Questions