Menu
Coddy logo textTech

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

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

On 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 3
challenge icon

Challenge

Easy

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