gpt4 book ai didi

R switch()如何将案例与向量进行比较?

转载 作者:行者123 更新时间:2023-12-04 10:50:01 24 4
gpt4 key购买 nike

我在 R 中的 switch 语句有一点问题。下面的代码就OK了……:

    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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com