In R, is there a way to make a switch statement such that the same block of code is executed for two different cases? Obviously I could copy and paste the whole body of code for both statements, but I was hoping there would be a neater way to do it.
I could also use an if-else block to avoid the repetition of large blocks of code but switches are generally faster in R.
It seems unlikely due to the way R parses a switch statement as a function, but I'm hoping that the developers of R took special care in parsing a switch statement to allow for multiple arguments to refer to the same block of code.
Switch case in R is a multiway branch statement. It allows a variable to be tested for equality against a list of values. Switch statement follows the approach of mapping and searching over a list of values.
The switch() function in R tests an expression against elements of a list. If the value evaluated from the expression matches item from the list, the corresponding value is returned.
The SWITCH function evaluates one value (called the expression) against a list of values, and returns the result corresponding to the first matching value. If there is no match, an optional default value may be returned.
The switch() function takes mainly two arguments: expression and list.
Provide named arguments without values, they fall through to the next expression with value
> switch("A", A=, B=, C="A OR B OR C", "Other")
[1] "A OR B OR C"
> switch("C", A=, B=, C="A OR B OR C", "Other")
[1] "A OR B OR C"
> switch("D", A=, B=, C="A OR B OR C", "Other")
[1] "Other"
This is described on the help page ?switch
If 'EXPR' evaluates to a character string then that string is
matched (exactly)to the names of the elements in '...'. If there
is a match then that element is evaluated unless it is missing, in
which case the next non-missing element is evaluated, so for
example 'switch("cc", a = 1, cc =, cd =, d = 2)' evaluates to '2'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With