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

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

它返回:
[1] "value = B"

...但我想将值与向量的值进行比较,如下所示:
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”或第一个代码来做到这一点,但我想了解这个错误。

最佳答案

我确定有更简单的方法,但您可以使用 alistdo.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() 如何将案例与向量进行比较?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24675022/

10-12 16:31