"conditional" plots
I am curious how to plot function that is defined something l开发者_Python百科ike this:
if(x < 1)
f(x) = x/10 * 1.2
if(x < 3)
f(x) = x/12 * 1.7
...
else
f(x) = x/15 * 2
If the function was simple, say f(x) = x/10 * x/5 , then there would be no problem, and one could use curve() method. However I am not sure what is the best way to deal with more complex functions, like the one above. Any ideas? Bonus points, if ggplot() could be used :)
Curve is still a possibility. (And as you read the statistical literature, this formulation shows up as I[x], "I" being for "indicator".)
curve( (x <1)*( (x/10)*1.2 ) + # one line for each case
(!(x <1)&(x<3) )*(x/12)*1.7 + # logical times (local) function
(x >=3)*(x/15)*2 ,
0,4) # limits
Are you looking for something like stepfun
?
fn <- stepfun(c(1,2,3,4,5),c(0,1,2,3,4,5))
plot(fn,verticals = FALSE)
The way you specify the function will be a bit different, but it's fairly easy to grasp once you've read ?stepfun
and plotted some examples yourself.
Matter of taste but I prefer ifelse
over Dwins indicators (like in mbq comment). For compare:
curve(
(x <1) * ( (x/10)*1.2 ) +
(!(x <1)&(x<3) ) * ( (x/12)*1.7 ) +
(x >=3) * ( (x/15)*2 ) ,
0,4)
# versus
curve(
ifelse(x < 1, (x/10)*1.2,
ifelse(x < 3, (x/12)*1.7,
(x/15)*2 )),
0,4)
精彩评论