Membership Tests
Part of the Logic & Flow section of Coddy's R journey. Lesson 14 of 64.
x %in% set checks every element of x and returns one logical value per element. all() asks whether every check is TRUE, any() whether at least one is.
required <- c("flour", "eggs", "milk")
pantry <- c("eggs", "salt", "flour")
print(required %in% pantry)
print(all(required %in% pantry))
print(any(required %in% pantry))Output:
[1] TRUE TRUE FALSE
[1] FALSE
[1] TRUEIndex with the negated check to list what is missing, in the order of the first vector:
required <- c("flour", "eggs", "milk", "sugar")
pantry <- c("eggs", "flour")
missing <- required[!(required %in% pantry)]
print(missing)Output:
[1] "milk" "sugar"setequal(a, b) checks whether two vectors hold the same values, ignoring order and repeats:
print(setequal(c("a", "b"), c("b", "a", "a")))
print(setequal(c("a", "b"), c("a", "c")))Output:
[1] TRUE
[1] FALSEOn an empty vector, all() is TRUE and any() is FALSE: with nothing required, nothing is missing.
which() turns a logical vector into the positions of its TRUE values, which tells you where the matches are:
required <- c("flour", "eggs", "milk")
pantry <- c("eggs")
print(which(!(required %in% pantry)))Output:
[1] 1 3Challenge
EasyComplete check_recipe(required, pantry). Return ready when every required ingredient is in the pantry. Otherwise return missing: followed by the missing ingredients, in the order of required, joined with , .
The supplied code reads the required ingredients and the pantry as comma-separated lines and prints the returned value.
Try it yourself
check_recipe <- function(required, pantry) {
# Write your code here
""
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(check_recipe(strsplit(input[1], ",")[[1]], strsplit(input[2], ",")[[1]]), 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