0
0
R Programmingprogramming~5 mins

Logical indexing in R Programming

Choose your learning style9 modes available
Introduction
Logical indexing helps you pick elements from a list or vector by using TRUE or FALSE values. It is like choosing items based on yes/no questions.
You want to find all numbers greater than 10 in a list.
You want to select names that start with a certain letter.
You want to filter data to keep only rows that meet a condition.
You want to replace some values in a vector based on a rule.
Syntax
R Programming
vector[logical_vector]
The logical_vector must be the same length as the vector you want to index or shorter (it will be recycled).
TRUE means keep the element, FALSE means skip it.
Examples
Selects all numbers in x that are greater than 10.
R Programming
x <- c(5, 12, 8, 20)
x[x > 10]
Selects names starting with the letter 'A'.
R Programming
names <- c("Anna", "Bob", "Amy")
names[substr(names, 1, 1) == "A"]
Selects elements at positions where the logical vector is TRUE.
R Programming
v <- c(1, 2, 3, 4, 5)
v[c(TRUE, FALSE, TRUE, FALSE, TRUE)]
Sample Program
This program picks numbers bigger than 10 from the list and prints them.
R Programming
numbers <- c(3, 15, 7, 22, 9)
# Select numbers greater than 10
big_numbers <- numbers[numbers > 10]
print(big_numbers)
OutputSuccess
Important Notes
Logical indexing is very useful for filtering data quickly.
If the logical vector is shorter than the vector, R recycles it, which can cause unexpected results.
You can combine multiple conditions using & (and) or | (or).
Summary
Logical indexing uses TRUE/FALSE to pick elements from a vector.
It helps filter or select data based on conditions.
Make sure the logical vector matches the length of the data vector or is a divisor of its length.