2017-09-01 44 views
1

我試圖在同一個圖表上繪製兩個函數(即2x + 1和3x - 0.5 * x^2)的圖形,但有兩個不同的範圍(x < = 3和x> 3)。到目前爲止,我已經定義了兩個功能如下:在R中繪製兩個函數的圖形

# Define first function with given range 
Line1 <- function(x) { 
    if (x <= 3) { 
     (3*x) + 1 } else { 
    }  
} 

# Define second function with given range 
Line2 <- function(x) { 
    if (x > 3) { 
     2*x - (0.5*(x^2)) } else { 
    }   
} 

# Plot functions 
ggplot(d,aes(x=x)) + stat_function(fun=rwrap(Line1,0,3),geom="line",col="blue") 
+ stat_function(fun=rwrap(Line2,3,5),geom="line",col="red")` 

當我運行代碼,我收到以下錯誤信息:

Error: Discrete value supplied to continuous scale In addition:

Warning messages:
1: In if (x <= 3) { : the condition has length > 1 and only the first element will be used
2: In if (x > 3) { : the condition has length > 1 and only the first element will be used

我試圖解決它,但我只是失去了在此刻。

+0

爲什麼你的代碼引用? – Gregor

+3

問題是你的函數沒有被矢量化。他們一次只能處理一個'x'值,但'Line1(0:10)'不起作用。使用'ifelse'作爲單個函數作爲if的向量化版本{if else else} {:foo = function(x)ifelse(x <= 3,3 x + 1,2 * x - 0.5 * x^2)'。 – Gregor

+0

對不起引用,我犯了一個複製和粘貼過程的錯誤。我明白你的陳述。但是,我將如何繪製不同顏色的線? – user8550070

回答

0

的問題是,你的功能沒有量化。他們會爲x在一個單一的價值在工作時間,但Line1(0:10)將無法​​正常工作。

使其與ifelse一個量化的功能,向量化版本的if{}else{}

foo = function(x) { 
    ifelse(x <= 3, 3 * x + 1, 2 * x - 0.5 * x^2) 
} 

你可以打破它,就像這樣:

bar = function(x) 3 * x + 1 
baz = function(x) 2 * x - 0.5 * x^2 
foo = function(x) ifelse(x <= 3, bar(x), baz(x)) 

雖然你當然會想使用更多有意義的名字比這些佔位符。