Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

650
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda