Menu
Coddy logo textTech

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] FALSE

An 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] 0

A 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] TRUE

A 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] 0
challenge icon

Challenge

Easy

Complete 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")
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