J.Z.
J.Z.

Reputation: 435

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.

Upvotes: 1

Views: 386

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269431

Either (1) rewrite ppt to vectorize it (not shown) or else (2) use Vectorize as shown below in which case ppt does not have to be modified. Also use this syntax.

curve(Vectorize(ppt)(x, tail = 0.2), ylab = "ppt")

screenshot

Upvotes: 2

PaulS
PaulS

Reputation: 25313

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)

Upvotes: 1

Related Questions