Search code examples
rconditional-statementsscatter-plotchain

Debugging A Conditional If Chain


I am trying to create a scatterplot and color the points within the specified ranges differently. I feel as though this chain should work, where I state the condition and the desired color in brackets.

Can anyone spot an error in my approach? or potentially the syntax?

plot(x, y, xlab="chr X position (Mb)",
     ylab="Diversity", pch=16, cex=0.7,
     col=if(x < 4), {"red"}
          else {
            if((x>3)&(x<89)) {"black"}
            else {
              if((x>88)&(x<94)) {"blue"}
              }
            else {
              if((x>93)&(x<155)) {"black"}
              }
            else {
              if(x>154) {"purple"}
              }
            }

Solution

  • Here's a solution using ifelse

    col = ifelse(x<4, "red",
           ifelse(x>3 & x<89 | x>93 & x<155, "black",
                  ifelse(x>88 & x<94, "blue", "purple")))
    

    You need ifelse becase ifelse is vectorized, if is not, therefore ifelse will check each element in your vector and filled with the corresponding color, while if only checks for the first element.

    A simple example to note this:

    x <- 1:6  # a sample vector
    
    # using `if` to check condition and assigning a value, it'll fail 
    if(x<4){
      "red"
    } else {
      "other color"
    }
    
    # suing `ifelse` for the same task. It'll win
    ifelse(x<4, "red", "other color")
    

    from the helpfile

    ifelse returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE