'R switch statement on empty string

The following code works:

switch("A", "A" = "a", "B" = "b", "C" = "c", "OTHER")

But this code doesn't:

switch("A", "" = "BLANK", "A" = "a", "B" = "b", "C" = "c", "OTHER")

It fails with the error:

Error: attempt to use zero-length variable name

Is there a reason to allow R switch statements to take empty strings?



Solution 1:[1]

The problem isn't whether switch can take a empty string, it's whether an empty string is a valid object name. It isn't. With this usage, you're doing the same thing as

"" = "BLANK"

What behavior are you trying to get from switch? Describe it, with a reproducible example, and we'll see if we can point you in the right direction!

In response to the comment: switch isn't written to be able to handle an empty string that returns something other than the default. If you want one value for the default and another for an empty string, you'll need a wrapper, like this:

f <- function(x){
    if(x == "") return("BLANK")
    switch(x, A = "a", B = "b", C = "c", "OTHER")
}

f("A")
# [1] "a"

f("ABC")
# [1] "OTHER"

f("")
# [1] "BLANK"

Solution 2:[2]

In some situations you might want to have the 'blank' check inside the switch statement and a possible solution could be:

switch(paste0(x, 'x'), x = 'BLANK', Ax = 'a', Bx = 'b', 'OTHER')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Chris