[R] Simple question regarding domain restrictions/piecewise functions in R
Rolf Turner
rolf.turner at xtra.co.nz
Mon Mar 26 10:35:52 CEST 2012
Does
f <- function(x){
ifelse((-1 < x & x < 1) | (2 < x & x < 3),x^2,NA)
}
plot(f,xlim=c(-3,5))
give you what you want?
cheers,
Rolf Turner
On 26/03/12 11:08, chad.mills wrote:
> I am a novice R user.
>
> I would like to be able to graph some simple piecewise functions/functions
> with domain restrictions in R, but I'm having trouble defining such
> functions. For example, I would like to define the following function:
>
> f(x)={x^2 if -1<x<x; 1 if 2<x<3}
>
> Notably, the function is undefined outside of domain (-1,1)U(2,3). My best
> attempt in R is something like this:
>
> f<-function(x) ifelse(-1<x& x<1,x^2,ifelse(2<=x& x<=3,1,as.null()))
>
> This approach works fine for values within the domain. But, naturally, when
> I try values outside of the domain I get an error. Consequently, when I try
> to graph such a function:
>
> plot(f)
>
> I get the following error:
>
> Error in ifelse(2<= x& x<= 3, 1, as.null()) :
> replacement has length zero
>
> I realize that I could create vectors of x-y points and plot using the
> plot(x,y) command, but it seems to me that I should be able to define a
> piecewise function symbolically and just graph it. Am I wrong? Any help
> would be greatly appreciated.
More information about the R-help
mailing list