如何将矢量作为参数传递给switch语句

时间:2021-10-04 07:25:07

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语句作为switch语句的参数:

switch(input,cases)

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

如果input = 1,上面只会输出任何内容,在这种情况下它会输出:

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语句中明确键入这样的情况:

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:

我想要的行为,我可以传递list / vector / whatever作为switch()中的参数,并实现以下行为:

switch(2,cases)
# [1] "two"

1 个解决方案

#1


7  

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:

switch函数接受一个表达式,指示从函数的其余参数中选择哪个参数号。如您所知,这意味着您需要在调用switch时将向量拆分为单独的参数。您可以通过将向量转换为带有as.list的列表,然后将每个列表元素作为单独的参数传递给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"

#1


7  

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:

switch函数接受一个表达式,指示从函数的其余参数中选择哪个参数号。如您所知,这意味着您需要在调用switch时将向量拆分为单独的参数。您可以通过将向量转换为带有as.list的列表,然后将每个列表元素作为单独的参数传递给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"