Masacroso - 1 month ago 13

R Question

I was reading other similar questions in this site about how to plot a piecewise function in R and I write this code

`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?

Answer Source

`<-`

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)}
```