Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 387
Dan Avatar asked Jan 31 '15 15:01

Dan


2 Answers

You could try:

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

enter image description here

like image 92
Steven Beaupré Avatar answered Nov 01 '22 08:11

Steven Beaupré


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.

like image 40
qwr Avatar answered Nov 01 '22 06:11

qwr