Using numeric values in switch statements

Viewed 49

I'm trying to use numeric values in a switch statement. However, as shown in this snippet, this does not work with my approach:

x <- as.character(1)
switch(x,
  x = "case 1",
  "default"
)
# "default"

What I'm expecting is this behavior:

switch("1",
  "1" = "case 1",
  "default"
)
# "case 1"

I'm confused by this, because I can't tell where the two approaches deviate, since this suggests they should work the same:

as.character(1) == "1"
# TRUE

Any ideas what I'm doing wrong here?

1 Answers

From help(switch):

If ‘EXPR’ evaluates to a character string then that string is matched (exactly) to the names of the elements in ‘...’.

So in your first case, the string "1" is matched to the string "x" (the name of the first element). That does not match, hence going to default.

Related