Selecting Cases in Switch case statement in R

376 views Asked by At

I am sorry if it seems like a foolish question but I wanna ask that does the case in the switch case statement always have to be a string for case selection in R? The following code throws an error:

day = 2
weekday <- switch(day,
                  1 = "Sunday",
                  2 = "Monday",
                  3 = "Tuesday",
                  4 = "Wednesday",
                  5 = "Thursday", 
                  6 = "Friday",
                  7 = "Saturday",
                  "Invalid Input!!")
print(weekday)

But this code works perfectly:

day = 2
weekday <- switch(day,
                  '1' = "Sunday",
                  '2' = "Monday",
                  '3' = "Tuesday",
                  '4' = "Wednesday",
                  '5' = "Thursday", 
                  '6' = "Friday",
                  '7' = "Saturday",
                  "Invalid Input!!")
print(weekday)

How come day, which is a number is matched with a character in the switch case?

2

There are 2 answers

0
Suresh_Patel On

Check the nif (nested if) and vswitch functions in package kit, I think this is what you are looking for. To access the documentation type ?kit::nif after installing the package.

3
Marius On

If the expression being tested in the switch() is a number, then cases are matched by position, so you can leave out the argument names and do:

day = 2
weekday <- switch(day,
                  "Sunday",
                  "Monday",
                  "Tuesday",
                  "Wednesday",
                  "Thursday", 
                  "Friday",
                  "Saturday",
                  "Invalid Input!!")
print(weekday)
# Output:
# [1] "Monday"