Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

651
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda