R switch() how to compare cases to a vector?

后端 未结 4 602
自闭症患者
自闭症患者 2021-01-21 02:28

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

    value = \"B\"
  switch(value, 
         \"A\"={
           print(\"         


        
4条回答
  •  孤独总比滥情好
    2021-01-21 03:24

    The == operator works on vectors, so what you need is just:

    > a <- c("A", "B", "C")
    > a
    [1] "A" "B" "C"
    > b <- "B"
    > b == a
    [1] FALSE  TRUE FALSE
    

    Alternatively, you can use which

    > which(a == b)
    [1] 2
    

    Note that can return several elements if a contains more than one instance of b

    You can then proceed using an if or ifelse or switch statement on the result.

    PS: you should avoid using list as a variable name, as it is a standard function in R

提交回复
热议问题