The curve function in base R

Deadly 提交于 2019-12-24 02:41:01

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/17951318/the-curve-function-in-base-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!