2

I'm going to depict a continuous graph on R using ggplot2 library, which is based on piecewise function.

fun1 <- function(x){
  ifelse(x<=-2, -1.5*(-x)^2, NA)
}
fun2 <- function(x){
  ifelse(x>-2, 6*x-5, NA)
}
gg <- ggplot(data.frame(x = c(-5, 5)), 
              aes(x = x))+
  stat_function(fun = fun1, n=1001)+
  stat_function(fun = fun2, n=1001)
print(gg)   

This shows the correct graph of the piecewise function.

enter image description here

But if I change the condition slightly different, such that ifelse(x<-2, -1.5*(-x)^2, NA) and ifelse(x>=-2, 6*x-5, NA), then suddenly the first part of the graph would not be depicted correctly.

enter image description here

This seems that the ifelse function now always returns -6 for all values x, irrespective of if it is <=-2 or not.

But why does this change suddenly happen? I tried to depict a continuous curve using standard plot function but still got the same result...

Blaszard
  • 30,954
  • 51
  • 153
  • 233

1 Answers1

5

This is what happens when you don't leave spaces between operators. As well as making your code less readable, you can sometimes confuse the parser. In your case, the parser interprets x<-2 as x <- 2, i.e. "assign 2 to x", not x < -2, i.e. "x is less than minus 2".

When you use an assigment as the first argument in ifelse, it will assess the "truthiness" of the value of the assignment, and since 2 is a positive integer, it will always evaluate to true. Since by the time the clause is evaluated, x is 2, then for all input values of the function, your output will be -1.5 * (-2)^2, i.e. -6.

If you use spaces (or parentheses) , this doesn't happen:

fun1 <- function(x){
  ifelse(x < -2, -1.5*(-x)^2, NA)
}
fun2 <- function(x){
  ifelse(x > -2, 6*x-5, NA)
}
gg <- ggplot(data.frame(x = c(-5, 5)), 
             aes(x = x))+
  stat_function(fun = fun1, n=1001)+
  stat_function(fun = fun2, n=1001)
print(gg)   

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • OMG, not having used R for years, I forgot it completely, or maybe didn't even know it. Sorry for a stupid question... – Blaszard Oct 23 '22 at 16:06
  • 2
    Eagle eye Allan Cameron! :-) – TarJae Oct 23 '22 at 16:09
  • 2
    @Blaszard I don't think it's stupid at all. It's easy to make this mistake if you are used to writing in a language that doesn't use the assignment operator (or doesn't evaluate assigments; arguably the code should throw a helpful error here) – Allan Cameron Oct 23 '22 at 16:11