2014-10-20 59 views
2

产生平线,我有以下代码:stat_function从功能

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) 

出乎意料地产生如下图:

enter image description here

但是,当我使用功能对自己的结果是预计:

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

怎么回事?

回答

4

注意以下警告:

> 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 

c(0,10)的第一个元素是比2不大于或等于,并且因为你的功能没有被设计为在值的向量操作,它只评估所述第一元素,并返回一个0 - 这是您致电print(graph)显示的内容。这实际上给了上述相同的警告信息:

> plot(graph) 
Warning message: 
In if (x >= 2) { : 
    the condition has length > 1 and only the first element will be used 

你只需要矢量化的功能:

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

+1

[R看起来像一个简单的语言,但它有一些疯狂古怪。 – 2014-10-21 06:25:10