[R] Plotting a segmented function
Ken Knoblauch
knoblauch at lyon.inserm.fr
Thu Mar 30 13:25:51 CEST 2006
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
--
Ken Knoblauch
Inserm U371
Cerveau et Vision
Dept. of Cognitive Neuroscience
18 avenue du Doyen Lépine
69500 Bron
France
tel: +33 (0)4 72 91 34 77
fax: +33 (0)4 72 91 34 61
portable: +33 (0)6 84 10 64 10
http://www.lyon.inserm.fr/371/
More information about the R-help
mailing list