R switch()

Like the switch statements in other languages, R has a similar construct in the form of switch() function.


Syntax of switch() function

switch (statement, list)

Here, the statement is evaluated and based on this value, the corresponding item in the list is returned.


Example: switch() function

If the value evaluated is a number, that item of the list is returned.

> switch(2,"red","green","blue")
[1] "green"

> switch(1,"red","green","blue")
[1] "red"

In the above example, "red","green","blue" form a three item list.

The switch() function returns the corresponding item to the numeric value evaluated.

If the numeric value is out of range (greater than the number of items in the list or smaller than 1), then, NULL is returned.

> x <- switch(4,"red","green","blue")
> x
NULL

> x <- switch(0,"red","green","blue")
> x
NULL

The result of the statement can be a string as well. In this case, the matching named item's value is returned.

> switch("color", "color" = "red", "shape" = "square", "length" = 5)
[1] "red"

> switch("length", "color" = "red", "shape" = "square", "length" = 5)
[1] 5
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges