Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a vector as a parameter in a switch statement

My googling of the question didn't return helpful results and the documentation for ?switch doesn't tell me how so I'm hoping I can get this answered here.

Say I have a vector:

cases<- c("one","two","three")

and I want to use a switch statement with those elements as the parameters for the switch statement:

switch(input,cases)

The above will only output anything if input=1 in which case it will output:

switch(1,cases)
# [1] "one" "two" "three"

Any other parameter will not return anything. The only way I can get the desired behavior is if I explicitly type the cases in the switch statement as such:

switch(2,"one","two","three")
# [1] "two"

I want the behavior where I can pass a list/vector/whatever as a parameter in switch() and achieve the following behavior:

switch(2,cases)
# [1] "two"
like image 311
edisondotme Avatar asked Sep 29 '15 04:09

edisondotme


People also ask

Can Switch Case pass variables?

The value for a case must be of the same data type as the variable in the switch. The value for a case must be constant or literal. Variables are not allowed.


1 Answers

The switch function takes an expression indicating which argument number to select from the remaining arguments to the function. As you note, this means you would need to split up your vector into separate arguments when invoking switch. You could achieve this by converting your vector to a list with as.list and then passing each list element as separate arguments to switch with do.call:

do.call(switch, c(1, as.list(cases)))
# [1] "one"
do.call(switch, c(2, as.list(cases)))
# [1] "two"
do.call(switch, c(3, as.list(cases)))
# [1] "three"

I don't really see the benefit of doing this over using simple vector indexing:

cases[1]
# [1] "one"
cases[2]
# [1] "two"
cases[3]
# [1] "three"
like image 179
josliber Avatar answered Nov 09 '22 19:11

josliber