Adding and Removing Keys
Part of the Logic & Flow section of Coddy's R journey. Lesson 9 of 64.
Assigning to a name updates its value when the key exists and adds a new entry when it does not:
stock <- c(apples = 12, pears = 3)
stock["pears"] <- 5
stock["plums"] <- 8
print(stock)Output:
apples pears plums
12 5 8 To change a value based on its current value, read and write the same key:
stock <- c(apples = 12, pears = 3)
stock["apples"] <- stock["apples"] - 2
print(stock[["apples"]])Output:
[1] 10A lookup table can start empty with c() and grow one key at a time:
ages <- c()
ages["Ada"] <- 36
ages["Linus"] <- 21
print(names(ages))Output:
[1] "Ada" "Linus"Remove an entry from a named vector by keeping every other name:
stock <- c(apples = 12, pears = 3, plums = 8)
stock <- stock[names(stock) != "pears"]
print(names(stock))Output:
[1] "apples" "plums" For a list, assigning NULL removes the entry:
user <- list(name = "Ada", temp = TRUE)
user[["temp"]] <- NULL
print(names(user))Output:
[1] "name"Challenge
EasyComplete apply_delivery(stock, item, qty). Add qty to the stock of item, or add item with the quantity qty when it is not stocked yet. Return the updated stock.
The supplied code reads the stock as name=quantity pairs, then the item and the quantity. It prints each entry of the returned stock as name: quantity, in the stock's order.
Try it yourself
apply_delivery <- function(stock, item, qty) {
# Write your code here
stock
}
# 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])
}
stock <- apply_delivery(stock, input[2], as.numeric(input[3]))
for (name in names(stock)) {
cat(name, ": ", stock[[name]], "\n", sep = "")
}
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