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

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

    Your mistake is that the switch alternatives require literal names and can't have a variable name. You're naming the arguments of the function and they internally become names of items in a list. In fact, the "" aren't necessary around your A, B, C in your first example. Knowing that, the problem becomes more obvious. Try assigning b <- "B" and then using b as the second switch item. That will fail as well because it's not going to resolve the variable name, just take it as a literal. In your case it fails with a syntax problem because alist[1] isn't a valid alternative label without quotes.

    Similar restrictions are placed on switch statements in other languages as well. Think of the alternatives in the switch as being labelled like names of items in a list structure. They can be pretty much anything quoted but they don't need quotes and then there are restrictions on what they can be. What they cannot be is variable.

    As you recognize in your question, there are alternative ways to do this. Here's a concise one that will be much faster than a switch statement (even if you did manage to solve the variable list items problem indirectly with a call function).

    i <- which(alist == value)
    if (length(i) == 1){
        print( paste0( 'value = ', alist[i]) )
    }else {
        print( 'Other !!' ) }
    

提交回复
热议问题