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
.
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.
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.
The SWITCH function evaluates one value (called the expression) against a list of values, and returns the result corresponding to the first matching value.
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.
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...
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"
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