Checking Keys
Part of the Logic & Flow section of Coddy's R journey. Lesson 8 of 64.
Before looking up a key that may be missing, check it with %in% against the names:
stock <- c(apples = 12, pears = 0)
print("pears" %in% names(stock))
print("plums" %in% names(stock))Output:
[1] TRUE
[1] FALSEAn if around the lookup gives a default value for a missing key, instead of an NA or an error:
stock <- c(apples = 12, pears = 0)
item <- "plums"
qty <- if (item %in% names(stock)) stock[[item]] else 0
print(qty)Output:
[1] 0A key that exists with the value 0 is different from a missing key: pears is known and out of stock, plums is not sold at all.
Lists use the same %in% names() check. A missing name in a list returns NULL rather than an error, so is.null() also works:
user <- list(name = "Ada", city = "London")
print(is.null(user[["email"]]))
print("city" %in% names(user))Output:
[1] TRUE
[1] TRUEA small helper keeps the check in one place when a program looks up many keys:
get_or <- function(x, key, default) {
if (key %in% names(x)) x[[key]] else default
}
stock <- c(apples = 12)
print(get_or(stock, "apples", 0))
print(get_or(stock, "kiwis", 0))Output:
[1] 12
[1] 0Challenge
EasyComplete stock_status(stock, item). Return unknown if item is not a key of stock, out of stock if its value is 0, and otherwise in stock: followed by the quantity.
The supplied code reads the stock as name=quantity pairs separated by commas, then the item, and prints the returned value.
Try it yourself
stock_status <- function(stock, item) {
# Write your code here
""
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
stock <- c()
for (pair in strsplit(input[1], ",")[[1]]) {
kv <- strsplit(pair, "=")[[1]]
stock[kv[1]] <- as.numeric(kv[2])
}
cat(stock_status(stock, input[2]), 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 Chart2Key-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