Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch Statement with repeated commands in R

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.

like image 315
Jon Claus Avatar asked Jun 14 '13 16:06

Jon Claus


People also ask

Can we use switch statement in R?

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.

What is the use of switch () function in R?

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.

What is the usage of switch function?

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.

What types of variables can be passed as the first argument to the switch function in R?

The switch() function takes mainly two arguments: expression and list.


1 Answers

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'.
like image 137
Martin Morgan Avatar answered Oct 26 '22 23:10

Martin Morgan