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] 14The 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] 4A 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] 15A missing name behaves differently in the two forms: prices["milk"] returns NA, and prices[["milk"]] stops with the error subscript out of bounds.
Challenge
EasyComplete 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")
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