R: Plot Piecewise function

元气小坏坏 提交于 2020-01-24 23:05:07

问题


I'm having some issues with the piecewise function I defined in R.

I've defined the function as:

g1 <- function(x) {
  if (x <= 0.25) {
    y <- gs1(x)
  }
  else if (x >= 0.75) {
    y <- gs3(x)
  }
  else {y <- gs2(x)}
  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 <- seq(0,1,length=200)
yy <- apply(as.matrix(xx),1,g1)
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.


回答1:


your issue is that you are looking for vectorized if-else, give ifelse a try, or apply your function using result<-sapply(vector, g1)




回答2:


You need to define the function so that it can directly accept a vector as an input.

One way is

g1 <- function(x) 
  (x <= 0.25)*gs1(x) + (x <= 0.75 & x > 0.25)*gs3(x) + (x > 0.75)*gs2(x)

Alternatively,

g1 <- function(x) {
  y <- gs1(x)
  y[x > 0.25] <- gs3(x[x > 0.25])
  y[x > 0.75] <- gs2(x[x > 0.75])
  y
}


来源:https://stackoverflow.com/questions/22329285/r-plot-piecewise-function

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