I have the following code:
library(\"ggplot2\")
f <- function(x)
{
if (x >= 2) {-1 + x + 0.3}
else {0}
}
graph <- ggplot(data.frame(x
Note the following warning:
> f(c(0,10))
[1] 0
Warning message:
In if (x >= 2) { :
the condition has length > 1 and only the first element will be used
The first element in c(0,10)
is not greater than or equal to 2, and since your function was not designed to operate on a vector of values, it only evaluated the first element and returned a single 0
- which is what your call to print(graph)
displays. This actually gave the same warning message as above:
> plot(graph)
Warning message:
In if (x >= 2) { :
the condition has length > 1 and only the first element will be used
You just need to vectorize your function:
f2 <- function(x)
{
ifelse(x>=2,-1+x+.3,0)
}
##
> f2(c(0,10))
[1] 0.0 9.3
##
graph2 <- ggplot(data.frame(x = c(0, 10)), aes(x))
graph2 <- graph2 + stat_function(fun=f2)
print(graph2)