The program I want to make gets an integer as an input and the output is the day of the week corresponding to the integer (ex. Input: x <- 3L, Output: Tuesday). I am required to use the switch() function for this, but I always get "Error: unexpected ',' in ". Below is the program I have made. Thank you!
x <- 5L
week_num2 <- switch(x,
1L = "Sunday",
2L = "Monday",
3L = "Tuesday",
4L = "Wednesday",
5L = "Thursday",
6L = "Friday",
7L = "Saturday",
stop("Invalid input")
)
week_num2
The switch() statement in R is parsed as a function call. Since you can't have argument names like 1L, it requires that the statement be written differently. You use all values from 1 to 7, so you can just leave off the argument name:
week_num2 <- switch(x,
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
)
(It would probably be a good idea to include the number as a comment, to make it easier to read.) This form doesn't support a default value; it will return NULL if you don't give it a number in range.
The other way to use it (which I recommend) is to use a character valued expression, e.g.
week_num2 <- switch(as.character(x),
"1" = "Sunday",
"2" = "Monday",
"3" = "Tuesday",
"4" = "Wednesday",
"5" = "Thursday",
"6" = "Friday",
"7" = "Saturday",
stop("Invalid input")
)
In this form, an unnamed argument is used as the default.