Using “curve” to plot a function: a tricky expression?

  • A+
Category:Languages

My question concerns something that should be fairly simple, but I can't make it work. What I mean is you can calculate x and y and then plot them with the plot function. But can this be done using the curve function?

I want to plot the following R function f2:

n <- 1 m <- 2 f2 <- function(x) min(x^n, x^(-m)) 

But this code fails:

curve(f2, 0, 10) 

Any suggestions?

 


As has been hinted at, the main reason why the call to curve fails is because curve requires a vectorized function (in this case feed in a vector of results and get out a vector of results), while your f2() function only inputs and outputs a scalar. You can vectorize your f2 on the fly with Vectorize

n <- 1 m <- 2  f2 <- function(x) min(x^n, x^(-m)) curve(Vectorize(f2)(x), 0, 10) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: