I'm having some issues with the piecewise function I defined in R.
I've defined the function as:
g1
if (x <= 0.25) {
y
}
else if (x >= 0.75) {
y
}
else {y
y
}
where gs1,gs2,gs3 are functions I defined earlier.
In order to plot the function g1, I tried:
curve(g1)
but R displays the following:
Warning message:
In if (x <= 0.25) { :
the condition has length > 1 and only the first element will be used
I think the problem might be that R requires the argument of the function as a number instead of a vector? I'm not sure whether I'm right or not.
I figured out the plotting problem by using the following method:
xx
yy
plot(xx,yy,type='l')
But I still want to ask is there any way to deal with this kind of problem since I found that my piecewise function defined is not okay for many other commands either. For example, say I would like to integrate g1 over 0 to 1, if I just try "integrate" function in R, same warning message appears.
解决方案
your issue is that you are looking for vectorized if-else, give ifelse a try, or apply your function using result