r语言怎么画分段函数

#遇到的问题
定义 𝑓(𝑥) =x^2 + 1,当 𝑥 > 1; 𝑓(𝑥) = 3𝑥2 − 1,当 0 < 𝑥 ≤ 1; 𝑓(𝑥) = 𝑥 − 1,当 𝑥 ≤ 0
.画出函数 𝑓(𝑥) 在 [-1,2] 上的图像
#my code

m <- function(x){
  if(x>1){f=x^2+1}
  if(x<=0){f=x-1}
  else{f=3*x^2-1}
  return(f)}
n <- Vectorize(m)
plot(m,-1,2,col=6)

#出现的问题
Error in if (x > 1) { : the condition has length > 1

##我知道如果函数只有两段的话可以用ifelse()来解决,但这个有三段没办法用此种方法,如果用curve函数的话,得分三次写,有点麻烦,有什么简便的方法来解决吗
希望得到大家的帮助,万分感谢!

可以使用向量化函数ifelse来解决

f <- function(x){ ifelse(x>1,x^2+1,ifelse(x<=0,x-1,3*x^2-1)) } plot(f,-1,2,type="l",col=6)

这里ifelse函数嵌套使用
如果x>1,则返回x^2+1,否则,进入下一层ifelse,
如果x<=0则返回x-1,否则返回3*x^2-1。

最后使用plot函数画图,指定type="l"来画出连续的曲线。