5

I have a series of nested if..else statements that I would like to replace with a case statement. Now R has a simple switch operator such as the following:

switch (i) {

    case 1:
        // action 1
        break;
    case 2:
        // action 2
        break;
    case 3:
        // action 3
        break;
    default:
        // action 4
        break;
}

However, my cases are more complicated conditionals, not simple literal values.

I need something like

switch {

    case i %in% someList:
        // action 1
        break;
    case i %in% someOtherList:
        // action 2
        break;
    case i > 42:
        // action 3
        break;
    default:
        // action 4
        break;
}

Does anyone know if something like this is possible in R? It would make the code I am working on much simpler to read.

As far as I can see, this question is not answered here: How to use the switch statement in R functions?

Thanks

Community
  • 1
  • 1
Karl
  • 5,573
  • 8
  • 50
  • 73
  • 2
    Is this a duplicate? OP asks for specific `switch` cases that can't be mapped to `switch` parameters – Carles Mitjans May 16 '17 at 08:50
  • Wouldnt this be a use case for simple `if` .. `else if` ... statements? – talat May 16 '17 at 08:55
  • @docendodiscimus of course that works well enough, and is what I am applying at the moment. But at a certain depth the nesting becomes quite difficult to read (not to mention maintain). A case statement would be a much more elegant solution – Karl May 16 '17 at 09:25
  • 1
    Then you might need to preprocess your conditions so that you can use a switch – talat May 16 '17 at 09:26

1 Answers1

1

Maybe it's not the best solution, but you can try with nested ifelse functions:

ifelse(i %in% someList, action1,
       ifelse(i %in% someOtherList, action2,
              ifelse(i > 42, action 3, default_action4)))
Carles Mitjans
  • 4,786
  • 3
  • 19
  • 38