Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a vector function from a scalar function in R

Tags:

r

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?

like image 215
Lost1 Avatar asked Jun 27 '26 08:06

Lost1


1 Answers

You would have to Vectorize the function f to get it to apply over a vector:

f = Vectorize(f)
print(f(bins))

Note that you could have also just used curve with sapply:

curve(sapply(x, f), from=-5, to=5)

Finally, if you wrote the function with ifelse like so:

f = function(x) {
    ifelse(x >= -5 & x <= -3, 3*(1-(x+4)^2)/8, ifelse(x>=3 & x<=5, 3*(1-(x-4)^2)/8, 0))
}

That would allow it to work on vectors without needing Vectorize.

like image 98
David Robinson Avatar answered Jun 28 '26 20:06

David Robinson