[R] Plotting a segmented function

Adaikalavan Ramasamy ramasamy at cancer.org.uk
Thu Mar 30 15:12:05 CEST 2006


Try 
 
   f <- function(x){
     if(x <= 0) return(0)
     if( 0 < x & x <= 1 ) return( 0.5*x^2 )
     if( 1 < x & x <= 2 ) return( -0.5*x^2 + 2*x - 1 )
     return(1)
   }

   xx <- seq(-1, 3, 0.1)
   yy <- sapply(xx, f)

Regards, Adai


On Thu, 2006-03-30 at 09:25 -0200, Ken Knoblauch wrote:
> You could try nested ifelse statements,
> 
> something like (untested)
> 
> x <- seq(-1, 3, 0.1)
>  y <- ifelse( x <= 3,
> 	    ifelse( x <= 2,
> 		ifelse( x <= 1,
> 		    ifelse( x <= 0, 0, x^2/2), 2 * x - (x^2/2) -1),  1) )
> plot(x, y)
> 
> **************************************
> This might be a trivial question, but I would appreciate if anybody
> could suggest an elegant way of plotting a function such as the
> following (a simple distribution function):
> F(x) = 0 if x<=0
>        =(x^2)/2 if 0<x<=1
>        =2x-((x^2)/2)-1 if 1<x<=2
>        =1 if x>2
> This is just an example. In this case it is a continuous function. But
> how to do it in general in an elegant way.
> I've done the following:
> x1 <- seq(-1,0,.01)
> f1 <- rep(0,101)
> x2 <- seq(0,1,.01)
> f2 <- 0.5*(x2^2)
> x3 <- seq(1,2,.01)
> f3 <- (2*x3)-(0.5*(x3^2))-1
> x4 <- seq(2,3,.01)
> f4 <- rep(1,101)
> x <- c(x1,x2,x3,x4)
> F <- c(f1,f2,f3,f4)
> plot(x,F,type='l')
> 
> But this seems very cumbersome.
> Any help is much appreciated.
> 
> Thanks
> Jacob
> 
>




More information about the R-help mailing list