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] 3A 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] TRUEAn 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.54Challenge
EasyComplete 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")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart10Advanced Control Flow
The switch() FunctionVectorized ifelse()repeat and breakRecursive FunctionsRecap - Grade Classifier2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler