Menu
Coddy logo textTech

Named Vector Lookups

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

A named vector stores values under names, which makes it a lookup table: the name is the key and the element is its value. Put the name in [[ ]] to get the value alone.

prices <- c(tea = 4, cake = 7)
print(prices[["cake"]])
print(names(prices))

Output:

[1] 7
[1] "tea"  "cake"

Single brackets return the element together with its name. [[ ]] returns only the value:

prices <- c(tea = 4, cake = 7)
print(prices["cake"])
print(prices[["cake"]] * 2)

Output:

cake 
   7 
[1] 14

The name can come from a variable, which is how a program looks up a key it read from input:

prices <- c(tea = 4, cake = 7)
item <- "tea"
print(prices[[item]])

Output:

[1] 4

A vector of names looks up several keys at once, repeats included, so sum() totals an order in one step:

prices <- c(tea = 4, cake = 7)
order <- c("tea", "cake", "tea")
print(sum(prices[order]))

Output:

[1] 15

A missing name behaves differently in the two forms: prices["milk"] returns NA, and prices[["milk"]] stops with the error subscript out of bounds.

challenge icon

Challenge

Easy

Complete line_total(item, qty). The function defines the menu below. Return the price of item times qty, formatted with two decimals: tea and 3 give 7.50.

menu <- c(tea = 2.5, coffee = 3, cake = 4.25, soup = 6)

Every item in the input is on the menu. The supplied code reads the item and the quantity and prints the returned value.

Try it yourself

line_total <- function(item, qty) {
  menu <- c(tea = 2.5, coffee = 3, cake = 4.25, soup = 6)
  # Write your code here
  ""
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(line_total(input[1], as.numeric(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