How to pass a vector as a parameter in a switch statement

My query question did not produce useful results, and the documentation for ?switch does not tell me how I hope I can get an answer here.

Let's say I have a vector:

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

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

 switch(input,cases) 

The above will only be output 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 injected the cases into the switch statement as such:

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

I need a behavior in which I can pass a list / vector / as a parameter to switch () and execute the following behavior:

 switch(2,cases) # [1] "two" 
+7
list vector parameters r switch-statement
source share
1 answer

The switch function takes an expression indicating which argument number is selected from the rest of the function arguments. As you noticed, this means that you need to split your vector into separate arguments when calling switch . You could achieve this by converting your vector to a list using as.list and then passing each element of the list as separate arguments to switch using 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 do not see this as an advantage using simple vector indexing:

 cases[1] # [1] "one" cases[2] # [1] "two" cases[3] # [1] "three" 
+7
source share

All Articles