2013-11-21 36 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="")