Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

R Switch


Share

The switch() Function

In the If...Else chapter, you learned to use else if to test many conditions.

When all the conditions check the same variable, the code gets long:

Example

fruit <- "banana"

if (fruit == "apple") {
  color <- "red"
} else if (fruit == "banana") {
  color <- "yellow"
} else if (fruit == "grape") {
  color <- "purple"
}

color
Try it Yourself »

The switch() function does the same thing in a shorter way. It compares a value with a list of names, and returns the value that belongs to the matching name:

Example

fruit <- "banana"

color <- switch(fruit,
  "apple" = "red",
  "banana" = "yellow",
  "grape" = "purple"
)

color
Try it Yourself »

R compares fruit with each name. "banana" matches, so switch() returns "yellow", which is stored in the color variable.


Default Value

If no name matches, you can add a last value without a name. This is the default value:

Example

fruit <- "kiwi"

color <- switch(fruit,
  "apple" = "red",
  "banana" = "yellow",
  "unknown color"
)

color
Try it Yourself »

Note: If no name matches and there is no default value, switch() returns NULL (nothing).



Same Result for Several Names

If a name has no value after the = sign, R uses the value of the next name.

Here, both "Sat" and "Sun" give "Weekend":

Example

day <- "Sun"

type <- switch(day,
  "Sat" = ,
  "Sun" = "Weekend",
  "Weekday"
)

type
Try it Yourself »

Switch with Numbers

If the first argument is a number, switch() returns the value at that position:

Example

day <- 3

switch(day, "Mon", "Tue", "Wed", "Thu", "Fri")
Try it Yourself »

day is 3, so switch() returns the third value, "Wed".



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.