stat_function produces flat line from function

后端 未结 1 357
滥情空心
滥情空心 2021-01-15 02:59

I have the following code:

library(\"ggplot2\")

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

graph <- ggplot(data.frame(x          


        
相关标签:
1条回答
  • 2021-01-15 03:50

    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

    0 讨论(0)
提交回复
热议问题