How to use the switch statement in R functions?
Solution 1:
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...
Solution 2:
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"