Menu
Coddy logo textTech

The switch() Function

Part of the Logic & Flow section of Coddy's R journey. Lesson 47 of 64.

switch(x, name = value, ...) compares the text x with the names and returns the value of the one that matches. It replaces a long chain of else if comparisons against the same variable:

size <- "m"
price <- switch(size, s = 2.5, m = 3, l = 3.5)
print(price)

Output:

[1] 3

A last value without a name is the default, used when nothing matches. Without a default, a non-matching switch() returns NULL invisibly:

day <- "fri"
print(switch(day, sat = "rest", sun = "rest", "work"))
print(is.null(switch("x", a = 1)))

Output:

[1] "work"
[1] TRUE

An empty value falls through to the next one, so several names can share a result:

kind <- function(day) switch(day, sat = , sun = "weekend", "weekday")
print(kind("sun"))
print(kind("tue"))

Output:

[1] "weekend"
[1] "weekday"

The values can be whole blocks of code in braces, and the result is the last expression of the block that runs:

area <- function(shape, a, b = a) {
  switch(shape,
    square = a^2,
    rect = a * b,
    circle = {
      r <- a / 2
      round(pi * r^2, 2)
    },
    NA)
}
print(area("rect", 3, 4))
print(area("circle", 10))

Output:

[1] 12
[1] 78.54
challenge icon

Challenge

Easy

Complete calculate(a, op, b). op is one of plus, minus, times and over. Return the result of applying it to a and b, or unknown operation for any other op. Dividing by zero returns cannot divide by zero.

The supplied code reads a, op and b (one per line) and prints the returned value.

Try it yourself

calculate <- function(a, op, b) {
  # Write your code here
  "unknown operation"
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(calculate(as.numeric(input[1]), input[2], as.numeric(input[3])), sep = "\n")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler