The %in% Operator
Part of the Fundamentals section of Coddy's R journey — lesson 70 of 78.
Sometimes you need to check whether values exist within a vector. The %in% operator provides a clean way to test for membership, returning TRUE for each element that matches and FALSE otherwise.
The basic syntax checks if values on the left exist in the vector on the right:
fruits <- c("apple", "banana", "cherry")
print("banana" %in% fruits)Output:
[1] TRUEYou can also check multiple values at once. The operator returns a logical vector with one result for each value being tested:
fruits <- c("apple", "banana", "cherry")
check <- c("banana", "grape", "apple")
print(check %in% fruits)Output:
[1] TRUE FALSE TRUEThis makes %in% perfect for filtering. Combined with logical indexing, you can extract elements that belong to a specific set:
numbers <- c(1, 5, 3, 8, 2, 9)
allowed <- c(1, 2, 3)
print(numbers[numbers %in% allowed])Output:
[1] 1 3 2The %in% operator is especially useful when validating user input or filtering data based on a predefined list of acceptable values.
Challenge
EasyYou will receive three lines of input:
- A comma-separated list of items in your inventory (e.g.,
apple,banana,milk,bread,eggs,cheese) - A comma-separated list of items on your shopping list (e.g.,
milk,butter,eggs,juice) - A comma-separated list of items that are on sale (e.g.,
bread,juice,yogurt)
Using the %in% operator:
- Create character vectors from each comma-separated input
- Check which shopping list items you already have in your inventory and print the logical vector result
- Filter and print the shopping list items that you do NOT have in your inventory (items you need to buy)
- Filter and print the items you need to buy that are also on sale
For example, if the inputs are:
apple,banana,milk,bread,eggs
milk,butter,eggs,juice,apple
bread,juice,yogurt,butterThe output should be:
[1] TRUE FALSE TRUE FALSE TRUE
[1] "butter" "juice"
[1] "butter" "juice"Explanation:
- Shopping list checked against inventory: milk (TRUE), butter (FALSE), eggs (TRUE), juice (FALSE), apple (TRUE)
- Items NOT in inventory (need to buy): butter, juice
- Items to buy that are on sale: butter and juice are both on the sale list
Use the ! operator with %in% to find items NOT in a vector.
Cheat sheet
The %in% operator checks if values exist within a vector, returning TRUE or FALSE:
fruits <- c("apple", "banana", "cherry")
print("banana" %in% fruits)Output:
[1] TRUECheck multiple values at once to get a logical vector:
fruits <- c("apple", "banana", "cherry")
check <- c("banana", "grape", "apple")
print(check %in% fruits)Output:
[1] TRUE FALSE TRUEUse %in% with logical indexing to filter elements:
numbers <- c(1, 5, 3, 8, 2, 9)
allowed <- c(1, 2, 3)
print(numbers[numbers %in% allowed])Output:
[1] 1 3 2Use ! with %in% to find items NOT in a vector:
items <- c("milk", "butter", "eggs")
inventory <- c("milk", "eggs")
print(items[!items %in% inventory])Output:
[1] "butter"Try it yourself
# Read input
con <- file("stdin", "r")
inventory_input <- suppressWarnings(readLines(con, n = 1))
shopping_list_input <- suppressWarnings(readLines(con, n = 1))
sale_items_input <- suppressWarnings(readLines(con, n = 1))
close(con)
# TODO: Write your code below
# 1. Create character vectors from each comma-separated input using strsplit()
# 2. Check which shopping list items you already have in inventory (use %in%)
# 3. Filter shopping list items you do NOT have in inventory (use ! with %in%)
# 4. Filter items you need to buy that are also on saleThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 27Bill Split Calculator
Welcome MessageGetting User Input13Vectors Advanced
Vector Slicing and IndexingLogical IndexingVector Arithmetic & RecyclingThe %in% Operator2Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values