Logical Indexing
Part of the Fundamentals section of Coddy's R journey — lesson 68 of 78.
Instead of specifying exact positions, you can use a logical vector to select elements. This technique, called logical indexing, lets you filter a vector based on conditions rather than positions.
When you apply a comparison to a vector, R returns a logical vector of the same length:
numbers <- c(10, 20, 30, 40, 50)
print(numbers > 25)Output:
[1] FALSE FALSE TRUE TRUE TRUEYou can use this logical vector directly inside square brackets to extract matching elements:
numbers <- c(10, 20, 30, 40, 50)
print(numbers[numbers > 25])Output:
[1] 30 40 50R keeps only the elements where the logical vector is TRUE. This approach is much cleaner than writing loops to filter data. You can combine conditions using logical operators:
numbers <- c(10, 20, 30, 40, 50)
print(numbers[numbers >= 20 & numbers <= 40])Output:
[1] 20 30 40Logical indexing is one of R's most powerful features for data manipulation, allowing you to filter datasets with simple, readable expressions.
Challenge
EasyYou will receive two lines of input:
- A comma-separated list of numbers (e.g.,
15,42,8,67,23,91,34,12,56) - Two threshold values separated by a comma representing a range (e.g.,
20,60)
Using logical indexing:
- Create a numeric vector from the comma-separated numbers
- Extract and print all elements that are less than the first threshold (lower bound)
- Extract and print all elements that are greater than the second threshold (upper bound)
- Extract and print all elements that are within the range (greater than or equal to the first threshold AND less than or equal to the second threshold)
For example, if the inputs are:
5,25,10,45,60,15,80,35,50
20,50The output should be:
[1] 5 10 15
[1] 60 80
[1] 25 45 35 50Explanation:
- Elements less than 20: 5, 10, 15
- Elements greater than 50: 60, 80
- Elements between 20 and 50 (inclusive): 25, 45, 35, 50
Use the & operator to combine conditions for the range filter.
Cheat sheet
Logical indexing allows you to filter a vector based on conditions rather than positions. When you apply a comparison to a vector, R returns a logical vector:
numbers <- c(10, 20, 30, 40, 50)
print(numbers > 25)
# Output: [1] FALSE FALSE TRUE TRUE TRUEUse the logical vector inside square brackets to extract matching elements:
numbers <- c(10, 20, 30, 40, 50)
print(numbers[numbers > 25])
# Output: [1] 30 40 50Combine conditions using logical operators like & (AND):
numbers <- c(10, 20, 30, 40, 50)
print(numbers[numbers >= 20 & numbers <= 40])
# Output: [1] 20 30 40Try it yourself
# Read input
con <- file("stdin", "r")
numbers_input <- suppressWarnings(readLines(con, n = 1))
thresholds_input <- suppressWarnings(readLines(con, n = 1))
close(con)
# Parse the comma-separated numbers into a numeric vector
numbers <- as.numeric(unlist(strsplit(numbers_input, ",")))
# Parse the threshold values
thresholds <- as.numeric(unlist(strsplit(thresholds_input, ",")))
lower_bound <- thresholds[1]
upper_bound <- thresholds[2]
# TODO: Write your code below
# 1. Use logical indexing to extract elements less than lower_bound and print
# 2. Use logical indexing to extract elements greater than upper_bound and print
# 3. Use logical indexing with & operator to extract elements within the range (inclusive) and printThis 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