Here is my function. It takes certain values on [-5,-3] and [3,5] and 0 elsewhere. The function is symmetric around the origin.
f<-function(x){
y=0
if (x>=-5 && x<=-3){
y=3*(1-(x+4)^2)/8
}
if (x>=3 && x<=5){
y=3*(1-(x-4)^2)/8
}
return(y)
}
Okay so I used the function sapply (bins, f)
where bins = seq(-5,5,by=0.05). This worked fine!
but when I tried to do f(bins), I got this ridiculous answer. It was correct for the [-5,-3] range.
My guess for this is that when the function f checked the first if condition, it checked it only for the first value of the bins vector, so for (-3,5] range, it incorrectly used the formula only intended for [-5,-3].
I am trying to get a way to draw a curve for these points, but when I used curve function, the curve is drawn using the wrong values we would get by using f(bins)
Can someone please tell me how to fix this?
You would have to Vectorize the function
fto get it to apply over a vector:Note that you could have also just used
curvewithsapply:Finally, if you wrote the function with
ifelselike so:That would allow it to work on vectors without needing
Vectorize.