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.
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.
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...
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)