0

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

ECII
  • 10,297
  • 18
  • 80
  • 121

2 Answers2

4

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.

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
0

You could just write a function that plots both curves:

myfun <- function(...) {
 plot(...)
 lines(...)
}

You have to give the right arguments of course. The result is two curves in one plot