How to use the switch statement in R functions?

Simon picture Simon · May 1, 2012 · Viewed 141.2k times · Source

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.

Answer

Tommy picture Tommy · May 1, 2012

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...