Search code examples
rfunctioncurve

The curve function in base R


Sorry this might be basic but I am a newbie. I will be making lots of curves so some advice will be useful for me.

I have a function which I want to plot:

f <- function(x) sum(4*sin(x*seq(1,21,2))/(pi*seq(1,21,2)))

using

curve(f, -pi, pi, n=100)

Unfortunately ,this does not work for me. Please advise. Thanks


Solution

  • You function isn't vectorized. At the moment it will only take a single scalar input and output a single return value. curve expects that it should be able to feed in a vector of the x values it wants to plot for and should receive a vector of response values. The easiest solution is to just use Vectorize to automatically convert your function into one that can take vector inputs.

    f2 <- Vectorize(f)
    curve(f2, -pi, pi, n = 100)
    

    However, you might just want to write a vectorized version of the function directly.