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

Dan picture Dan · Jan 31, 2015 · Viewed 12.4k times · Source

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.

Answer

Steven Beaupr&#233; picture Steven Beaupré · Jan 31, 2015

You could try:

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

enter image description here