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.
______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.