10

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.

Dan
  • 101
  • 1
  • 1
  • 3

2 Answers2

9

You could try:

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

enter image description here

Steven Beaupré
  • 21,343
  • 7
  • 57
  • 77
  • 1
    That works, thanks! I tried curve(Vectorize(g), 0, 2), which didn't work. Any idea why? – Dan Jan 31 '15 at 16:31
  • 2
    From `?curve`: The way curve handles expr has caused confusion. It first looks to see if expr is a name (also known as a symbol), in which case it is taken to be the name of a function, and expr is replaced by a call to expr with a single argument with name given by xname. Otherwise it checks that expr is either a call or an expression, and that it contains a reference to the variable given by xname (using all.vars): anything else is an error. – Steven Beaupré Jan 31 '15 at 16:39
  • 1
    @StevenBeaupré : Thanks for the quote from the manual. It does not explain though why `Vectorize()` is necessary. Probably because `curve()` invokes its `expr` argument by passing to it a vector of all abscissa points _at once_; but I am just guessing here. – András Aszódi May 28 '19 at 13:41
1

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.

qwr
  • 9,525
  • 5
  • 58
  • 102