R switch / case with advanced conditions

Viewed 8267

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

1 Answers
Related