简体   繁体   English

在R中绘制分段函数

[英]Plotting a piecewise function in R

I was reading other similar questions in this site about how to plot a piecewise function in R and I write this code 我正在阅读本网站中有关如何在R中绘制分段函数的其他类似问题,我编写此代码

myfunction = function(x){(x<-1)*(x^2+2*x)+(-1<=x & x<=1)*x+(x>1)*(-1)}
g=Vectorize(myfunction)
plot(g,-5,5)

However the plot is just a straight line, that is, it doesnt plot the defined function. 然而,绘图只是一条直线,也就是说,它没有绘制定义的函数。 What Im doing wrong? 我做错了什么?

<- is assignment and won't be interpreted as "less than negative". <-是分配,不会被解释为“小于负”。 Add a space in there and you'll see what you expect. 在那里添加一个空格,你会看到你的期望。

myfunction = function(x){(x< -1)*(x^2+2*x)+(-1<=x & x<=1)*x+(x>1)*(-1)}

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

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