Error with curve( ): 'expr' did not evaluate to an object of length 'n'

14,766

Solution 1

You could try:

h <- Vectorize(g); curve(h, 0, 2)

enter image description here

Solution 2

curve() uses an expr that is expected to be vectorized, so it can pass in n points all at once as x.

Observe f(1:10) gives a vector of length 10, while g(1:10) only gives a single value, which curve() does not like. A simple fix is to vectorize the function, ex.

curve(Vectorize(g)(x), 0, 2)

where 'expr' must be a function, or a call or an expression containing 'x'. curve(Vectorize(g), 0, 2) won't work because Vectorize(g) needs to be evaluated with x first.

Share:
14,766
Dan
Author by

Dan

Updated on July 25, 2022

Comments

  • Dan
    Dan almost 2 years

    I have a function that has a vector in the numerator and the sum of the vector in the denominator. So each component is one component of the vector divided by a function that depends on the sum of the components. I want to plot a curve representing the function in the first component holding fixed the other components. Why doesn't this code work?

    y <- vector(length=2)
    y0 <- c(1,2)
    f <- function(y) y/(1+sum(y))
    g <- function(x) f(c(x,y0[2]))[1]
    curve(g, 0, 2)
    

    Both f and g evaluate as expected at numerical values, but the curve function gives the error:

    Error in curve(g, 0, 2) : 
      'expr' did not evaluate to an object of length 'n'
    

    I tried Vectorizing g with no success. Appreciate any help.