2
votes

I have the following code:

library("ggplot2")

f <- function(x)
{
    if (x >= 2) {-1 + x + 0.3}
    else {0}    
}

graph <- ggplot(data.frame(x = c(0, 10)), aes(x))
graph <- graph + stat_function(fun=f)
print(graph)

That unexpectedly produces the following graph:

enter image description here

But when I use the function on its own the result is the expected:

> f(1)
[1] 0
> 
> f(3)
[1] 2.3
> 
> f(7)
[1] 6.3

How come?

1

1 Answers

5
votes

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)

enter image description here