2013-11-21 35 views
0

我需要定義下面的函數,需要在R.定義R中的函數,繪製它的劇情

0 <= x <= 975 f(x)=975 
975 < x <= 1025 f(x)=x 
1025 < x   f(x) = 1025 

繪製的圖表爲它我試圖把它定義如下的方式,但它給了我語法錯誤 -

myfunc <- function() 
{ 
if (xx <= 975) 
{return(975)} 
else if (xx < 975 and xx <= 1025) 
{return(xx)} 
else {return (1025)} 
} 

我指的是下面的頁面的語法。 http://www.dummies.com/how-to/content/how-to-chain-if133else-statements-in-r.html

定義函數後,我想繪製它。下面的命令會起作用嗎?

curve(expr=myfunc,from=0,to=1100,xlim=c(0,1100),ylim=c(0,1100),xlab="",ylab="") 

請讓我知道,如果我需要提供任何進一步的信息。

+0

第五行應該是'否則如果(975 Backlin

回答

0

&已經向你指出。你的函數也需要一個參數,它需要被矢量化以與curve一起工作。您可以使用ifelse而不是ifelse來實現矢量化。然而,相信以下是更好:

myfunc <- function(x) { 
    #find the intervals in which each value is 
    interv <- as.integer(cut(x, c(0,975,1025,Inf),include.lowest = TRUE)) 
    #in arithmetic operations logical values TRUE/FALSE are coerced to 1/0 
    (interv==1L)*975 + (interv==2L)*x + (interv==3L)*1025 
} 

#note the n=1e3 which achieves a better resolution of the curve 
curve(expr=myfunc,from=0,to=1100, 
     xlim=c(0,1100),ylim=c(0,1100),xlab="",ylab="", n=1e3) 

enter image description here

+0

非常感謝Roland提供的信息,並讓我知道切割功能。 來Ifelse,我相信我可以只用於一個條件,而不是他們的倍數,即我只能指定如果x <975和行動取決於x的值。因爲按照它的語法,首先我們指定測試條件,然後指定它在條件爲真或假時應該返回的值。 讓我知道,如果我的理解是不正確的。 謝謝! –

+0

你可以像'if'和'else'那樣嵌套'ifelse'。在stackoverflow上應該有很多例子。 – Roland

0

你得到一個錯誤,因爲布爾值,而不是寫爲 「和」,而是 「&」:

else if (xx < 975 & xx <= 1025)

除此之外,你的意思是:

else if (xx > 975 and xx <= 1025)

而且還你應該提供你的論點的功能:

myfunc <- function(xx)

0

這裏是你正在尋找全面的解決方案:

myfunc <- Vectorize(function(xx) { 
    if (xx <= 975){ 
    return(975) 
    } else if (xx > 975 && xx <= 1025){ 
    return(xx) 
    } else { 
    return (1025) 
    } 
}) 

curve(myfunc, 0, 1100, xlim=c(0,1100), ylim=c(0,1100), xlab="", ylab="")