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

后端 未结 4 566
自闭症患者
自闭症患者 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:09

    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))
    

    Examples:

    > 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"
    

提交回复
热议问题