Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

649
Views
How to use switch() function in R?

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
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!