R switch()如何将案例与向量进行比较? [英] R switch() how to compare cases to a vector?
本文介绍了R switch()如何将案例与向量进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 R 中的 switch 语句有一点问题.下面的代码就OK了……:
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.
推荐答案
我确定有更简单的方法,但你可以使用 alist
和 do.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屋!
查看全文