Search code examples
rfunctionplotcurve

curve() using a function with argument in R


ppt=function(v, tail = 0.5){
  if (tail == 1){
    6/pi^2/v^2
  } else {
    if (v < 11) {
      (1-tail)*(11-v)/55
      } else {tail*6/pi^2/(v-10)^2}
  }
}
curve(ppt(tail = 0.2))
Error in curve(ppt(tail = 0.2)) : 
  'expr' must be a function, or a call or an expression containing 'x'

How should I plot a smooth curve for the function ppt() with different values of variable tail?

Thank you.


Solution

  • Maybe the following trick?

    w = 0.2
    g <- function(z) ppt(z, tail = w)
    curve(g)
    

    And do not forget to replace, as @MrFlick points out in the comment:

    if (v < 11) {
          (1-tail)*(11-v)/55
          } else {tail*6/pi^2/(v-10)^2}
    

    by

    ifelse(v < 11, (1-tail)*(11-v)/55, tail*6/pi^2/(v-10)^2)