Search code examples
rvectorization

Why does this statement involving the function curve() return an error in R?


I am just curious to know why this statement returns an error in R

>   curve(function(x) x^2, from = -2, to = 2)

##Error in curve(function(x) x^2, from = -2, to = 2) : 
 #'expr' did not evaluate to an object of length 'n'

I do know that this statement works perfectly.

>   curve(x^2, from = -2, to = 2)

As far as I know, the first argument of the function curve() in R should be a vectorized function. Therefore, function(x) x^2 as an argument should be a vectorized function as well because it returns a numeric vector whose length is equal to the length of the input numeric vector.

However, I can't be sure because I do not have a rigorous background in programming. Clearly, I am wrong.


Solution

  • I think expr= as the first argument to curve is looking for the name of a function, not a function itself.

    expr: The 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'.

    So a function needs to be declared externally for it to work:

    f <- function(x) x^2
    curve(f, from=-2, to=2) 
    

    Otherwise you can plot the function directly as plot.function, which actually calls curve inside the function as the last line:

    plot.function
    #function (x, y = 0, to = 1, from = y, xlim = NULL, ylab = NULL, 
    #    ...) 
    #{
    #    <snip>
    #    curve(expr = x, from = from, to = to, xlim = xlim, ylab = ylab, 
    #        ...)
    #}
    

    Like:

    plot(function(x) x^2, xlim=c(-2,2))