Home > Enterprise >  How can I plot a graph of a function using multiple conditions?
How can I plot a graph of a function using multiple conditions?

Time:10-28

I’m going to make a continuous graph with conditional log, in particular:

f <- function(x) {
  if (0 < x && x <= 2) {
    return (log(x));
  } else {
    return (x^2*log(x));
  }
}

Now, I want to plot it:

ggplot(data.frame(x=seq(0,5,length.out=1000)), aes(x))   geom_function(fun=f)

enter image description here

This code shows the graph fine on the part that is from x = 2 on, but for some reasons even on x between 0 and 2, it uses the second function x^2*log(x), not the first one.

This is more easily seen if I change the seq to seq(0, 2.1, length.out=1000).

enter image description here

But why does this happen and how can I fix it? I think I'm fine with the if statement with multiple conditions...

CodePudding user response:

if is not vectorized. try ifelse instead:

f <- function(x) {
  ifelse(test = 0 < x & x <= 2, 
         yes  = log(x), 
         no   = (x^2) * log(x))
}

df <- data.frame(x = seq(0, 5, length.out = 10000))
ggplot(df, aes(x))   
  geom_function(fun = f)

Vectorized means that ifelse takes a logical vector and applies the corresponding logic to each element of the vector, whether test was TRUE or FALSE.

if instead can handle just a single TRUE or FALSE. In case a vector is provided, only the first element of the vector is considered. Hence you probably received the following warning:

#> Warning messages:
#> 1: In 0 < x && x <= 2 : 'length(x) = 1000 > 1' in coercion to 'logical(1)'
  • Related