Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the switch statement in R functions?

I would like to use for my function in R the statement switch() to trigger different computation according to the value of the function's argument.

For instance, in Matlab you can do that by writing

switch(AA)         case '1'    ...    case '2'    ...    case '3'   ...   end 

I found this post - switch() statement usage - that explain how to use switch, but not really helpful to me as I want to perform more sophisticated computation (matrix operations) and not a simple mean.

like image 277
Simon Avatar asked May 01 '12 04:05

Simon


People also ask

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.

Can we use switch statement in R?

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

What is the use 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.

Does R have a case statement?

Switch case statements are a substitute for long if statements that compare a variable to several integral values. Switch case in R is a multiway branch statement. It allows a variable to be tested for equality against a list of values.


2 Answers

Well, switch probably wasn't really meant to work like this, but you can:

AA = 'foo' switch(AA,  foo={   # case 'foo' here...   print('foo') }, bar={   # case 'bar' here...   print('bar')     }, {    print('default') } ) 

...each case is an expression - usually just a simple thing, but here I use a curly-block so that you can stuff whatever code you want in there...

like image 161
Tommy Avatar answered Nov 16 '22 02:11

Tommy


those various ways of switch ...

# by index switch(1, "one", "two") ## [1] "one"   # by index with complex expressions switch(2, {"one"}, {"two"}) ## [1] "two"   # by index with complex named expression switch(1, foo={"one"}, bar={"two"}) ## [1] "one"   # by name with complex named expression switch("bar", foo={"one"}, bar={"two"}) ## [1] "two" 
like image 35
petermeissner Avatar answered Nov 16 '22 00:11

petermeissner