Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The curve function in base R

Tags:

function

r

curve

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

like image 316
user2633313 Avatar asked Jan 21 '26 16:01

user2633313


1 Answers

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.

like image 141
Dason Avatar answered Jan 24 '26 07:01

Dason