1

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?

Dason
  • 60,663
  • 9
  • 131
  • 148
user3685285
  • 6,066
  • 13
  • 54
  • 95
  • would handling empty string before calling `switch` works for you? seems like you cant have empty variable name – chinsoon12 Mar 08 '18 at 03:44

2 Answers2

3

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"
De Novo
  • 7,120
  • 1
  • 23
  • 39
  • To add to @DanHall's answer, OPs first `switch` command should really be `switch("A", A = "a", B = "b", C = "c", "OTHER")`. – Maurits Evers Mar 07 '18 at 22:42
  • Ok understood, but what about the second one? what if the element passed into the switch statement was an empty string? I want it to return "BLANK". How would I do that? – user3685285 Mar 07 '18 at 23:52
  • Try the wrapper function I added to this response. If that doesn't do what you need it to, maybe edit your question or write a new question that gives more context? I hope that was helpful! – De Novo Mar 08 '18 at 05:48
0

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')
Chris
  • 139
  • 9