Search code examples
rplotcurve

Plot a change point curve in one command


I want to plot a curve that has a change point at x=5

Until now I am using the code

curve(exp(0.68+0.92*x), from=0,to=5, xlim=c(0,12), ylim=c(0,500))
curve(exp(0.68+0.92*x-0.7*(x-5)), from=5,to=12, add=T)

Is it possible to write it in one line (one curve command)? I was thinking

something like this

curve(exp(0.47+0.8*x-0.7*(x-5)*if(x<5,0,1)), from=0,to=12, xlim=c(0,12), ylim=c(0,500))

but it doesn't work for R


Solution

  • Using ifelse you can create one data series:

    values = ifelse(x <= 5, exp(0.68+0.92*x), exp(0.68+0.92*x-0.7*(x-5))
    

    and plot them:

    curve(values)
    

    and if you insist on a one-liner you can combine the ifelse and the call to curve:

    curve(ifelse(x <= 5, exp(0.68+0.92*x), exp(0.68+0.92*x-0.7*(x-5)))
    

    although separating the code into two lines makes it easier to read imo.