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.
You could try:
h <- Vectorize(g); curve(h, 0, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With