简体   繁体   English

R:绘制分段函数

[英]R: Plot Piecewise function

I'm having some issues with the piecewise function I defined in R. 我在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. 其中gs1,gs2,gs3是我之前定义的函数。

In order to plot the function g1, I tried: 为了绘制函数g1,我尝试:

curve(g1)

but R displays the following: 但是R显示以下内容:

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? 我认为问题可能是R要求函数的参数为​​数字而不是向量? 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. 例如,假设我想将g1集成到0到1之间,如果我只是尝试在R中“集成”功能,则会出现相同的警告消息。

您的问题是您正在寻找向量化if-else,尝试ifelse或使用result<-sapply(vector, g1)应用函数

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM