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?
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: