R Switch

R switch statement selects one of the cases, based on the value of an expression.

There are two ways in which one of the cases is selected: based on index or matching value.

  1. Switch based on Index – If the cases are just values and the expression evaluates to a number, then the expression’s value is used as index to select the case.
  2. Switch based on Matching Value – If cases have both case value and output value like case_1=value1, then the expression value is matched against cases. When there is a match with a case, the corresponding value is the output.

In this tutorial, we will go through these two types of switch statements in detail.

Switch based on Index

The syntax of Switch statement which selects one of the cases based on index is

switch(expression, value1, value2, value3, ...)

Example 1

In this example, we will use switch statement based on index. The value of y, is taken as index.

y <- 3

x <- switch(
	y,
	"Good Morning",
	"Good Afternoon",
	"Good Evening",
	"Good Night"
)

print(x)

Output

R switch example

Example 2

In the following R switch statement, we have an expression with two variables: a and b. The expression is evaluated to an integer and this integer is used as an index to select the value.

a <- 1
b <- 2

x <- switch(
	a+b,
	"Good Morning",
	"Good Afternoon",
	"Good Evening",
	"Good Night"
)

print(x)

Output

R switch with expression
ADVERTISEMENT

Switch based on Matching Value

The syntax of switch statement based on matching value is

switch(expression, case1=value1, case2=value2, ..., caseN=valueN)

Example 1

In this example, we will write a switch statement that selects on of the many values by matching expression’s value with the cases.

y <- "12"

x <- switch(
	y,
	"9"="Good Morning",
	"12"="Good Afternoon",
	"18"="Good Evening",
	"21"="Good Night"
)

print(x)

Output

R switch based on value

Example 2

In the following R switch statement, we used a string concatenation expression.

a <- "1"
b <- "8"

x <- switch(
	paste(a,b,sep=""),
	"9"="Good Morning",
	"12"="Good Afternoon",
	"18"="Good Evening",
	"21"="Good Night"
)

print(x)

Output

R switch with expression

Conclusion

In this R Tutorial, we learned R switch statement, its syntax and examples to understand how to use switch statement.