# [R] Plotting a segmented function

Uwe Ligges ligges at statistik.uni-dortmund.de
Thu Mar 30 09:30:57 CEST 2006

```Jacob van Wyk wrote:

> 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.

Define a function such as

f <- function(x){

(x>2) +
(2*x-((x^2)/2)-1) * ((1 < x) & (x <= 2)) +
((x^2)/2) *  ((0 < x) & (x <= 1))
}

curve(f, from = -1, to = 3)

> Thanks
> Jacob
>
>
> Jacob L van Wyk
> Department of Statistics
> University of Johannesburg APK
> P O Box 524
> Auckland Park 2006
> South Africa
> Tel: +27-11-489-3080
> Fax: +27-11-489-2832
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help