R switch() 如何将案例与向量进行比较? [英] R switch() how to compare cases to a vector?

查看:37
本文介绍了R switch() 如何将案例与向量进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 R 中的 switch 语句有一个小问题.下面的代码是好的...:

I've got a little issue with the switch statement in R. The following code is OK ... :

    value = "B"
  switch(value, 
         "A"={
           print("value = A")
         },
         "B"={
           print("value = B")
         },
         "C"={
           print("value = C")
         },
         {
           print("Other !!!")
        }
        )

它返回:

[1] "value = B"

...但我想像这样将值与向量的值进行比较:

... but I would like to compare value to a vector's values like this :

mychr = c("A","B", "C")
  value = "B"
  switch(value, 
         mychr[1]={
           print(mychr[1])
         },
         mychr[2]={
           print(mychr[2])
         },
         mychr[3]={
           print(mychr[3])
         },
         {
           print("Other !!!")
         }
         )

这行不通.

我可以用if else"或第一个代码来做到这一点,但我想了解这个错误.

I can do this with "if else", or with the first code but I would like to understand the mistake.

推荐答案

我相信有更简单的方法,但你可以使用 alistdo.call

Im sure there are easier ways but you can use alist and do.call

xlist = c("A","B", "C")
value = "B"
myList <- alist(print(xlist[1]), print(xlist[2]), print(xlist[3]), print("Other !!!"))
myList <- setNames(myList, c(xlist, ''))
do.call(switch, c(EXPR = value, myList))

示例:

> value = "D"
> do.call(switch, c(EXPR = value, myList))
[1] "Other !!!"
> value = "A"
> do.call(switch, c(EXPR = value, myList))
[1] "A"
> value = "C"
> do.call(switch, c(EXPR = value, myList))
[1] "C"
> value = "B"
> do.call(switch, c(EXPR = value, myList))
[1] "B"

这篇关于R switch() 如何将案例与向量进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆